package com.uzai.console.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.entity.*;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.EmojiUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.TbUserInfo.TbUserInfoIdDto;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.TbUserInfo.TbUserInfoUpdateDto;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.groupsendjob.GroupSendChildidPushDto;
import com.uzai.console.dto.feign.groupsendjob.NewGroupSendMsgDto;
import com.uzai.console.dto.feign.userextinfo.AlipayUserAuthDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.feign.uzaimanage.SysRunlogWarningDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.user.UserUpdateMarketingTagDto;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.dto.user.wechatuser.*;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.entity.es.WechatBlacklistPrv;
import com.uzai.console.entity.es.WechatBlacklistPub;
import com.uzai.console.entity.wxpubmanage.WxpubInfoEntity;
import com.uzai.console.enums.FriendRequestScene;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.*;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.*;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.tbuserinfo.TbUserInfoVo;
import com.uzai.console.vo.user.MarketingRewardVo;
import com.uzai.console.vo.user.SysTagShow;
import com.uzai.console.vo.user.SysTagVo;
import com.uzai.console.vo.user.UserTreeVo;
import com.uzai.console.vo.user.useraccdetail.UserAccDetailInfoVo;
import com.uzai.console.vo.user.wechatuser.MinMaxCreateTimeVo;
import com.uzai.console.vo.user.wechatuser.WechatUserInfoVo;
import com.uzai.console.vo.user.wechatuser.WechatUserPageVo;
import com.uzai.console.vo.user.wechatuser.WechatUserSimpleVo;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsInfoVo;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class WechatUserServiceImpl extends CommonService implements WechatUserService {

    private Logger logger = LoggerFactory.getLogger(WechatUserServiceImpl.class);

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private WechatUserTreeInfoService wechatUserTreeInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private PyqExpressionMapper pyqExpressionMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private UzaiCashierServerFeignService uzaiCashierServerFeignService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private MarketingRewardsService marketingRewardsService;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private MarketingTagMapper marketingTagMapper;
    @Autowired
    private UzaiManageFeignService uzaiManageFeignService;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private UserOperatorService userOperatorService;

    @Autowired
    private RiskLevelMapper riskLevelMapper;


    /**
     * 分页查询微信用户列表
     *
     * @param wechatUserQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<WechatUserPageVo> findWechatUserList(WechatUserQuery wechatUserQuery) {

        logger.info("---查询个人微信会员列表---wechatUserQuery={}", JSONObject.toJSONString(wechatUserQuery));

        //接口返回查询对象
        Page<WechatUserPageVo> pageVo = new Page<>();
        //执行分页查询对象
        Page<WechatUser> page = new Page<>();
        wechatUserQuery.convert(page);

        //判断是否有淘宝会员id条件
        if(StringUtils.isNotBlank(wechatUserQuery.getSpecialId())){
            //清空其他条件
            WechatUserQuery wechatUserQuery_specialId = new WechatUserQuery();
            wechatUserQuery_specialId.setMerId(wechatUserQuery.getMerId());
            wechatUserQuery_specialId.setSize(wechatUserQuery.getSize());
            wechatUserQuery_specialId.setCurrent(wechatUserQuery.getCurrent());
            wechatUserQuery_specialId.setOrder(wechatUserQuery.getOrder());
            wechatUserQuery_specialId.setAsc(wechatUserQuery.isAsc());
            wechatUserQuery_specialId.setOrderByField(wechatUserQuery.getOrderByField());
            wechatUserQuery_specialId.setOrderItemList(wechatUserQuery.getOrderItemList());
            wechatUserQuery_specialId.setSpecialId(wechatUserQuery.getSpecialId());
            //重新生成查询条件
            wechatUserQuery = wechatUserQuery_specialId;

            //查询淘宝会员信息
            TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
            tbUserInfoQuery.setMerId(wechatUserQuery.getMerId());
            tbUserInfoQuery.setSpecialId(wechatUserQuery.getSpecialId());
            List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(tbUserInfoQuery);
            if(tbUserInfoList != null && tbUserInfoList.size() > 0){
                List<Long> userIdList = new ArrayList<>();
                for (TbUserInfo tbUserInfo : tbUserInfoList) {
                    userIdList.add(tbUserInfo.getUserId());
                }
                wechatUserQuery.setIdList(userIdList);
            }else{//未查询到淘宝会员id,则返回空
                return pageVo;
            }
        }
        // 判断是否带有风险条件id
        if (wechatUserQuery.getRiskLevelId() != null) {
            RiskLevel riskLevel = riskLevelMapper.selectById(wechatUserQuery.getRiskLevelId());
            if (riskLevel != null) {
                wechatUserQuery.setMaxScore(riskLevel.getMaxScore());
                wechatUserQuery.setMinScore(riskLevel.getMinScore());
            }
        }

        //新建返回到页面的LIST对象
        List<WechatUserPageVo> wechatUserPageVoList = new ArrayList<WechatUserPageVo>();

        //判断是否需要脱敏
        Boolean tuominFlag_mobile = true;
        String cmstype_user_mobile_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_USER_MOBILE, wechatUserQuery.getMerId()));
        if(StringUtils.isNotBlank(cmstype_user_mobile_verified)){
            tuominFlag_mobile = false;
        }
        // 	"riskLevelId": 1795304946337513473
        List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);

        if(wechatUserList != null){

            for(WechatUser wechatUser : wechatUserList){
                WechatUserPageVo wechatUserPageVo = new WechatUserPageVo();
                BeanUtils.copyProperties(wechatUser, wechatUserPageVo);

                //处理淘礼金脱敏显示
                //是否脱敏处理
                if(tuominFlag_mobile){
                    wechatUserPageVo.setMobile(DesensitizeUtil.around(wechatUserPageVo.getMobile(), 3, 4));
                }

                try {
                    //身份名称
                    wechatUserPageVo.setIdentityName(IdentityEnum.getById(wechatUserPageVo.getIdentity()).getDesc());

                    //会员类型名称
                    if(wechatUserPageVo.getUserType() != null){
                        UserType userType = userTypeMapper.selectById(wechatUserPageVo.getUserType(), wechatUserQuery.getMerId());
                        if(userType != null){
                            wechatUserPageVo.setUserTypeName(userType.getName());
                        }
                    }

                    //上级用户
                    if(wechatUserPageVo.getParentId() != null){
                        if(wechatUserPageVo.getParentId().longValue() != 0){
                            WechatUser wechatUserParent = wechatUserMapper.selectById(wechatUserPageVo.getParentId(), wechatUserQuery.getMerId());
                            if(wechatUserParent != null){
                                wechatUserPageVo.setParentName(wechatUserParent.getNickName());
                            }
                        }else{
                            wechatUserPageVo.setParentId(null);
                        }
                    }

                    //代理
                    if(wechatUserPageVo.getAgentId() != null){
                        if(wechatUserPageVo.getAgentId().longValue() != 0){
                            WechatUser wechatUserAgent = wechatUserMapper.selectById(wechatUserPageVo.getAgentId(), wechatUserQuery.getMerId());
                            if(wechatUserAgent != null){
                                wechatUserPageVo.setAgentName(wechatUserAgent.getNickName());
                            }
                        }else{
                            wechatUserPageVo.setAgentId(null);
                        }
                    }

                    //合伙人
                    if(wechatUserPageVo.getPartnerId() != null){
                        if(wechatUserPageVo.getPartnerId().longValue() != 0){
                            WechatUser wechatUserPartner = wechatUserMapper.selectById(wechatUserPageVo.getPartnerId(), wechatUserQuery.getMerId());
                            if(wechatUserPartner != null){
                                wechatUserPageVo.setPartnerName(wechatUserPartner.getNickName());
                            }
                        }else{
                            wechatUserPageVo.setPartnerId(null);
                        }
                    }

                    //查询机器人ID
                    if(wechatUserPageVo.getDeviceUniqueId() != null){
                        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUserPageVo.getDeviceUniqueId(), wechatUserQuery.getMerId());
                        if(deviceWechatInfo != null){
                            wechatUserPageVo.setDeviceId(deviceWechatInfo.getDeviceId());
                            wechatUserPageVo.setDeviceName(deviceWechatInfo.getDeviceName());
                            wechatUserPageVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
                        }
                    }

                    //用户类型组信息
                    if(wechatUserPageVo.getUserType() != null){
                        UserType userType = userTypeMapper.selectById(wechatUserPageVo.getUserType(), wechatUserQuery.getMerId());
                        if(userType != null){
                            Long userTypeGroupId = userType.getGroupId();
                            if(userTypeGroupId != null){
                                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, wechatUserQuery.getMerId());
                                if(userTypeGroup != null){
                                    wechatUserPageVo.setUserTypeGroupId(userTypeGroup.getId());
                                    wechatUserPageVo.setUserTypeGroupName(userTypeGroup.getName());
                                }
                            }
                        }
                    }

                    //注册来源名称
                    if(wechatUserPageVo.getRegChannel() != null){
                        FriendRequestScene friendRequestScene = FriendRequestScene.getById(wechatUserPageVo.getRegChannel());
                        if(friendRequestScene != null){
                            wechatUserPageVo.setRegChannelName(friendRequestScene.getLabel());
                        }
                    }

                    //标签List
                    try {
                        wechatUserPageVo.setTagsArr(JSONObject.parseArray(wechatUserPageVo.getTags(), String.class));
                    }catch (Exception e){ //如果不是JSON格式

                    }

                    //会员标签
                    if(StringUtils.isNotBlank(wechatUser.getSysTags())){
                        try {
                            List<SysTagVo> sysTagVoList =  JSONObject.parseArray(wechatUser.getSysTags(), SysTagVo.class);
                            if(sysTagVoList != null && sysTagVoList.size() > 0){
                                List<SysTagShow> sysTagShowList = new ArrayList<>();
                                List<Long> sysTagsArr = new ArrayList<>();
                                for (SysTagVo sysTagVo : sysTagVoList) {
                                    SysTagShow sysTagShow = new SysTagShow();
                                    BeanUtils.copyProperties(sysTagVo, sysTagShow);
                                    //查询标签名称
                                    MarketingTag marketingTag = marketingTagMapper.selectById(sysTagVo.getId(), wechatUserQuery.getMerId());
                                    if(marketingTag != null){
                                        sysTagShow.setName(marketingTag.getName());
                                        if(!Tools.getStr(marketingTag.getName()).startsWith("SYS_")){ //去掉SYS_开头的会员标签
                                            sysTagShowList.add(sysTagShow);
                                            sysTagsArr.add(sysTagVo.getId());
                                        }
                                    }
                                }
                                wechatUserPageVo.setSysTagsArr(sysTagsArr);
                                wechatUserPageVo.setSysTagVoArr(sysTagShowList);
                            }
                        }catch (Exception e){ //如果不是JSON格式

                        }
                    }

                    //查询用户额外信息
                    UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                    userExtInfoQueryDto.setMerId(wechatUserQuery.getMerId());
                    userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getId()); //个人用户
                    userExtInfoQueryDto.setBizUserId(wechatUser.getBizUserId());
                    List<String> keys = new ArrayList<>();
                    keys.add("ValidOrderCount"); //首字母大写
                    userExtInfoQueryDto.setKeys(keys);

                    StopWatch stopWatch = new StopWatch();
                    stopWatch.start();

                    UzaiRespVo<EsUserExtInfo> uzaiRespVo =  userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                    stopWatch.stop();
                    //logger.info("-获取订单总量接口分析：" + stopWatch.prettyPrint());

                    //超过10秒的事务，报警
                    if(stopWatch.getTotalTimeSeconds() > 10){
                        SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                        sysRunlogWarningDto.setText("获取订单总量接口分析，超过10秒的请求监控！\n类名：WechatUserServiceImpl"+"\n方法：findWechatUserList"+"\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                        UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                        logger.info("--调用官方钉钉报警超过10秒未处理完成的获取订单总量接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                    }

                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                        EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                        if(esUserExtInfo != null){
                            wechatUserPageVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                        }
                    }

                    //是否在白名单当中
                    String id_white = wechatUserQuery.getMerId() + "_" + wechatUser.getBizUserId();
                    Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                    if(white_map != null){
                        wechatUserPageVo.setBlacklistFlag(3); //白名单
                        wechatUserPageVo.setBlacklistId(wechatUser.getBizUserId());
                    }

                    //是否在全网黑名单当中
                    String id_blacklistPub = wechatUser.getBizUserId();
                    Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                    if(pub_map != null){
                        wechatUserPageVo.setBlacklistFlag(2); //共享全网黑名单
                        wechatUserPageVo.setBlacklistId(wechatUser.getBizUserId());
                    }

                    String id_blacklistPrv = wechatUserQuery.getMerId() + "_" + wechatUser.getBizUserId();
                    Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                    if(prv_map != null){ //在私有黑名单当中
                        wechatUserPageVo.setBlacklistFlag(1); //私有黑名单
                        wechatUserPageVo.setBlacklistId(id_blacklistPrv);
                    }
                }catch (Exception e){

                }

                //查询会员扩展信息
                String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
                String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId());
                //查询会员基本信息
                Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id, null);
                EsUserExtInfo esUserExtInfo = JSONObject.parseObject(JSONObject.toJSONString(dataMp_ext), EsUserExtInfo.class);
                if (esUserExtInfo != null) {
                    //最后查券时间也小于页面查询时间且大于0
                    int lastQueryTime = Tools.getInteger(esUserExtInfo.getLastQueryTime());
                    wechatUserPageVo.setLastQueryTime(lastQueryTime);
                }

//                // 查询风险等级
//                if (wechatUser.getRiskScore() != null) {
//                    RiskLevel riskLevel = riskLevelMapper.selectByScore(wechatUser.getRiskScore());
//                    if (riskLevel != null) {
//                        wechatUserPageVo.setRiskLevelName(riskLevel.getName());
//                    }
//
//                }


                wechatUserPageVoList.add(wechatUserPageVo);
            }
        }

        //返回到页面分页对象
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wechatUserPageVoList);
        //将返回对象排序(如果没有，则默认id排序降序)
        if(StringUtils.isBlank(wechatUserQuery.getOrderByField()) &&  (wechatUserQuery.getOrderItemList() == null || wechatUserQuery.getOrderItemList().size() == 0)){
            Tools.sort(wechatUserPageVoList, "id", wechatUserQuery.isAsc()? "asc":"desc");

        }
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询下级用户列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param findSonUserListQuery
     * @return null
     */
    public Page<WechatUserPageVo> findSonUserList(FindSonUserListQuery findSonUserListQuery){
        Long parentId = findSonUserListQuery.getParentId();
        if(parentId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入上级会员id");
        }

        Long merId = findSonUserListQuery.getMerId();
        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Integer type = Tools.getInteger(findSonUserListQuery.getType());

        WechatUser wechatUser = wechatUserMapper.selectById(parentId, merId);
        if(wechatUser != null){
            if(Tools.getInteger(wechatUser.getIdentity()).intValue() == IdentityEnum.BUYER.getId().intValue()){ //此会员是买家，则通过parentId来查询
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                BeanUtils.copyProperties(findSonUserListQuery, wechatUserQuery);
                wechatUserQuery.setMerId(findSonUserListQuery.getMerId());
                wechatUserQuery.setParentId(findSonUserListQuery.getParentId());
                wechatUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                wechatUserQuery.setSize(findSonUserListQuery.getSize());
                wechatUserQuery.setCurrent(findSonUserListQuery.getCurrent());
                return  findWechatUserList(wechatUserQuery);
            }else if(Tools.getInteger(wechatUser.getIdentity()).intValue() == IdentityEnum.AGENT.getId().intValue()){
                if(type == 2){ //下级代理
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, wechatUserQuery);
                    wechatUserQuery.setParentId(null);
                    wechatUserQuery.setMerId(findSonUserListQuery.getMerId());
                    wechatUserQuery.setAgentId(findSonUserListQuery.getParentId());
                    wechatUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    wechatUserQuery.setSize(findSonUserListQuery.getSize());
                    wechatUserQuery.setCurrent(findSonUserListQuery.getCurrent());
                    return  findWechatUserList(wechatUserQuery);
                }else if(type == 3 || type == 4){ //直推或者非直推买家
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, wechatUserQuery);
                    wechatUserQuery.setParentId(null);
                    wechatUserQuery.setMerId(findSonUserListQuery.getMerId());
                    wechatUserQuery.setAgentId(findSonUserListQuery.getParentId());
                    wechatUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    wechatUserQuery.setSize(findSonUserListQuery.getSize());
                    wechatUserQuery.setCurrent(findSonUserListQuery.getCurrent());
                    if(type == 3){ //直推
                        wechatUserQuery.setBuyerType(1);
                    }else{
                        wechatUserQuery.setBuyerType(2); //非直推
                    }
                    return  findWechatUserList(wechatUserQuery);
                }
            }else{ //合伙人
                if(type == 1){ //买家
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, wechatUserQuery);
                    wechatUserQuery.setParentId(null);
                    wechatUserQuery.setMerId(findSonUserListQuery.getMerId());
                    wechatUserQuery.setPartnerId(findSonUserListQuery.getParentId());
                    wechatUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    wechatUserQuery.setSize(findSonUserListQuery.getSize());
                    wechatUserQuery.setCurrent(findSonUserListQuery.getCurrent());
                    return  findWechatUserList(wechatUserQuery);
                }else if(type == 2){ //代理
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, wechatUserQuery);
                    wechatUserQuery.setParentId(null);
                    wechatUserQuery.setMerId(findSonUserListQuery.getMerId());
                    wechatUserQuery.setPartnerId(findSonUserListQuery.getParentId());
                    wechatUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    wechatUserQuery.setSize(findSonUserListQuery.getSize());
                    wechatUserQuery.setCurrent(findSonUserListQuery.getCurrent());
                    return  findWechatUserList(wechatUserQuery);
                }
            }
        }

        //返回到页面分页对象
        Page<WechatUserPageVo> pageVo = new Page<>();
        BeanUtils.copyProperties(findSonUserListQuery, pageVo);
        return pageVo;
    }

    /**
     * 查询微信用户详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserIdDto
     * @return null
     */
    public WechatUserInfoVo findWechatUserInfo(@RequestBody WechatUserIdDto wechatUserIdDto){

        if(wechatUserIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询页面用户
        WechatUser wechatUser =  wechatUserMapper.selectById(wechatUserIdDto.getId(), wechatUserIdDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }


        //返回给页面参数
        WechatUserInfoVo wechatUserInfoVo = new WechatUserInfoVo();
        BeanUtils.copyProperties(wechatUser, wechatUserInfoVo);

        // 查询撸狗风险值
//        if (wechatUser.getRiskScore() != null) {
//            RiskLevel riskLevel = riskLevelMapper.selectByScore(wechatUser.getRiskScore());
//            if (riskLevel != null) {
//                wechatUserInfoVo.setRiskLevelName(riskLevel.getName());
//            }
//        }


        //判断是否需要脱敏,默认脱敏
        Boolean tuominFlag_wxid = true;
        String CMSTYPE_WECHATUSER_WXID_VERIFIED =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_WECHATUSER_WXID_VERIFIED, wechatUserIdDto.getMerId(), wechatUserInfoVo.getId()));
        if(StringUtils.isNotBlank(CMSTYPE_WECHATUSER_WXID_VERIFIED)){
            tuominFlag_wxid = false;
        }
        //是否脱敏处理
        if(tuominFlag_wxid){
            wechatUserInfoVo.setWxid("");
        }else{
            wechatUserInfoVo.setWxid(wechatUser.getBizUserId());
        }

        //查询机器人ID
        if(wechatUser.getDeviceUniqueId() != null){
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), wechatUser.getMerId());
            if(deviceWechatInfo != null){
                wechatUserInfoVo.setDeviceId(deviceWechatInfo.getDeviceId());
                wechatUserInfoVo.setDeviceName(deviceWechatInfo.getDeviceName());
                wechatUserInfoVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
            }
        }

        //用户类型组信息
        if(wechatUser.getUserType() != null){
            UserType userType = userTypeMapper.selectById(wechatUser.getUserType(), wechatUserIdDto.getMerId());
            if(userType != null){
                Long userTypeGroupId = userType.getGroupId();
                if(userTypeGroupId != null){
                    UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, wechatUserIdDto.getMerId());
                    if(userTypeGroup != null){
                        wechatUserInfoVo.setUserTypeGroupId(userTypeGroup.getId());
                        wechatUserInfoVo.setUserTypeGroupName(userTypeGroup.getName());
                    }
                }
            }
        }

        //注册来源名称
        if(wechatUserInfoVo.getRegChannel() != null){
            FriendRequestScene friendRequestScene = FriendRequestScene.getById(wechatUserInfoVo.getRegChannel());
            if(friendRequestScene != null){
                wechatUserInfoVo.setRegChannelName(friendRequestScene.getLabel());
            }
        }

        //标签
        try {
            wechatUserInfoVo.setTagsArr(JSONObject.parseArray(wechatUser.getTags(), String.class));
        }catch (Exception e){ //如果不是JSON格式
        }

        //会员标签
        if(StringUtils.isNotBlank(wechatUser.getSysTags())){
            try {
                List<SysTagVo> sysTagVoList =  JSONObject.parseArray(wechatUser.getSysTags(), SysTagVo.class);
                if(sysTagVoList != null && sysTagVoList.size() > 0){
                    List<SysTagShow> sysTagShowList = new ArrayList<>();
                    List<Long> sysTagsArr = new ArrayList<>();
                    for (SysTagVo sysTagVo : sysTagVoList) {
                        sysTagsArr.add(sysTagVo.getId());
                        SysTagShow sysTagShow = new SysTagShow();
                        BeanUtils.copyProperties(sysTagVo, sysTagShow);
                        //查询标签名称
                        MarketingTag marketingTag = marketingTagMapper.selectById(sysTagVo.getId(), wechatUser.getMerId());
                        if(marketingTag != null){
                            sysTagShow.setName(marketingTag.getName());
                        }
                        sysTagShowList.add(sysTagShow);
                    }
                    wechatUserInfoVo.setSysTagsArr(sysTagsArr);
                    wechatUserInfoVo.setSysTagVoArr(sysTagShowList);
                }
            }catch (Exception e){ //如果不是JSON格式

            }
        }

        //上级、代理、合伙人如果为0，变成null
        if(wechatUserInfoVo.getParentId() != null && wechatUserInfoVo.getParentId().longValue() == 0){
            wechatUserInfoVo.setParentId(null);
        }
        if(wechatUserInfoVo.getAgentId() != null && wechatUserInfoVo.getAgentId().longValue() == 0){
            wechatUserInfoVo.setAgentId(null);
        }
        if(wechatUserInfoVo.getPartnerId() != null && wechatUserInfoVo.getPartnerId().longValue() == 0){
            wechatUserInfoVo.setPartnerId(null);
        }

        //上级买家树
        if(StringUtils.isNotBlank(wechatUserInfoVo.getParentInfo())){
            String parentInfo = wechatUserInfoVo.getParentInfo();
            //买家树长度
            int parentInfoLength = parentInfo.length();
            if(parentInfoLength > 19){//长度大于19，上级不止一层，判断是否有下划线拼接
                //统计下划线的总数
                int underlineCount = Tools.stringContainCharTimes(parentInfo, "_");
                //计算上级买家树长度层级数
                int parentCount = (parentInfoLength - underlineCount) / 19;
                //判断计算出的买家树层级数与下划线的个数是否匹配，就是层数为下线线数+1
                if(parentCount == underlineCount + 1){ //如果买家数匹配上下划线数量，则不处理
                    String[] parentIdList = wechatUserInfoVo.getParentInfo().split("_");
                    if(parentIdList != null && parentIdList.length > 0){
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList){
                            UserTreeVo userTreeVo = new UserTreeVo();
                            WechatUser wechatUser_parent = wechatUserMapper.selectById(Long.valueOf(parentId), wechatUserIdDto.getMerId());
                            if(wechatUser_parent != null){
                                userTreeVo.setId(wechatUser_parent.getId());
                                userTreeVo.setNickName(wechatUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        wechatUserInfoVo.setParentInfoList(parentInfoList);
                    }
                }else{//未匹配上，则需要清除下划线，重新修改买家树信息
                    parentInfo = parentInfo.replaceAll("_","");
                    String[] parentIdList = Tools.stringToStringArray(parentInfo, 19);
                    if(parentIdList != null && parentIdList.length > 0){
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList){
                            UserTreeVo userTreeVo = new UserTreeVo();
                            WechatUser wechatUser_parent = wechatUserMapper.selectById(Long.valueOf(parentId), wechatUserIdDto.getMerId());
                            if(wechatUser_parent != null){
                                userTreeVo.setId(wechatUser_parent.getId());
                                userTreeVo.setNickName(wechatUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        wechatUserInfoVo.setParentInfoList(parentInfoList);

                        //手动修改买家树
                        String parentInfoNew = StringUtils.join(parentIdList, "_");
                        wechatUser.setParentInfo(parentInfoNew);
                        wechatUser.setUpdateTime(DateUtil.getNowTime());
                        wechatUserMapper.updateParetInfo(wechatUser);
                    }
                }
            }else{//就一层上级，没有下划线，直接查询该上级信息
                UserTreeVo userTreeVo = new UserTreeVo();
                WechatUser wechatUser_parent = wechatUserMapper.selectById(Long.valueOf(parentInfo), wechatUserIdDto.getMerId());
                if(wechatUser_parent != null){
                    List<UserTreeVo> parentInfoList = new ArrayList<>();
                    userTreeVo.setId(wechatUser_parent.getId());
                    userTreeVo.setNickName(wechatUser_parent.getNickName());
                    parentInfoList.add(userTreeVo);
                    wechatUserInfoVo.setParentInfoList(parentInfoList);
                }
            }
        }

        //上级代理树
        if(StringUtils.isNotBlank(wechatUserInfoVo.getAgentInfo())){
            String[] agentIdList = wechatUserInfoVo.getAgentInfo().split("_");
            if(agentIdList != null && agentIdList.length > 0){
                List<UserTreeVo> agentInfoList = new ArrayList<>();
                for (String agentId : agentIdList){
                    UserTreeVo userTreeVo = new UserTreeVo();
                    WechatUser wechatUser_agent = wechatUserMapper.selectById(Long.valueOf(agentId), wechatUserIdDto.getMerId());
                    if(wechatUser_agent != null){
                        userTreeVo.setId(wechatUser_agent.getId());
                        userTreeVo.setNickName(wechatUser_agent.getNickName());
                        agentInfoList.add(userTreeVo);
                    }
                }
                wechatUserInfoVo.setAgentInfoList(agentInfoList);
            }
        }

        //是否在全网黑名单当中
        String id_blacklistPub = wechatUser.getBizUserId();
        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
        if(pub_map != null){
            wechatUserInfoVo.setBlacklistFlag(2); //共享全网黑名单
            wechatUserInfoVo.setBlacklistId(wechatUser.getBizUserId());
        }

        //是否在白名单当中
        String id_white = wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
        if(white_map != null){
            wechatUserInfoVo.setBlacklistFlag(3); //白名单
            wechatUserInfoVo.setBlacklistId(wechatUser.getBizUserId());
        }

        String id_blacklistPrv = wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
        Map<String,Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
        if(prv_map != null){ //在私有黑名单当中
            wechatUserInfoVo.setBlacklistFlag(1); //私有黑名单
            wechatUserInfoVo.setBlacklistId(id_blacklistPrv);
        }

        //会员互通信息
        if(StringUtils.isNotBlank(wechatUser.getUzaiUnionId())){
            try{
                //互通的公众号会员信息
                WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(wechatUser.getUzaiUnionId(), wechatUser.getMerId());
                if(wxpubUser != null){
                    wechatUserInfoVo.setWxpubUserId(wxpubUser.getId());
                }

                //互通的企业微信会员信息
                WxworkUser wxworkUser = wxworkUserMapper.selectByUzaiUnionId(wechatUser.getUzaiUnionId(), wechatUser.getMerId());
                if(wxworkUser != null){
                    wechatUserInfoVo.setWxworkUserId(wxworkUser.getId());
                }
            }catch (Exception e){
                logger.error("--通过unionId查询互通企业或者互通公众号出现异常--, uzaiUnionId={}", wechatUser.getUzaiUnionId());
            }

        }

        //如果会员昵称和会员头像都为空，则从ES中更新下信息
        if(StringUtils.isBlank(wechatUser.getNickName()) || StringUtils.isBlank(wechatUser.getHeadImg())){
            //从ES中获取个人微信信息
            if(wechatUser.getDeviceUniqueId() != null){
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), wechatUserIdDto.getMerId());
                if(deviceWechatInfo != null){
                    if(StringUtils.isNotBlank(deviceWechatInfo.getDeviceId())){
                        String esId = wechatUser.getMerId() + "_" + deviceWechatInfo.getDeviceId() + "_" + wechatUser.getBizUserId();
                        try{

                            //通过查询运营商其他索引分片获取分片索引
                            String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wechatUserIdDto.getMerId());
                            Map<String,Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, esId, null);
                            WxContactsInfoVo wxContactsInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxContactsInfoVo.class);
                            if(wxContactsInfoVo != null){
                                //更新微信信息
                                wechatUser.setWxid(wxContactsInfoVo.getWxid());
                                wechatUser.setNickName(wxContactsInfoVo.getNick());
                                wechatUser.setHeadImg(wxContactsInfoVo.getHimg());
                                wechatUser.setRemark(wxContactsInfoVo.getRemark());
                                wechatUserMapper.updateById(wechatUser);

                                //返回给页面
                                wechatUser.setWxid(wxContactsInfoVo.getWxid());
                                wechatUserInfoVo.setNickName(wxContactsInfoVo.getNick());
                                wechatUserInfoVo.setHeadImg(wxContactsInfoVo.getHimg());
                                wechatUserInfoVo.setRemark(wxContactsInfoVo.getRemark());
                            }
                        } catch (Exception e){
                            logger.error("从ES中同步通讯录:error={}", e);
                        }
                    }
                }
            }
        }

        try {
            //关联其他机器人
            List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>();
            wechatUserInfoVo.setDeviceInfoList(deviceInfoVoList);
            if(StringUtils.isNotBlank(wechatUser.getDeviceInfos())){
                List<Long> deviceInfoList = JSONObject.parseArray(wechatUser.getDeviceInfos(), Long.class);
                if(deviceInfoList != null && deviceInfoList.size() > 0){
                    for (Long deviceUniqueId : deviceInfoList) {
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, DeviceTypeEnum.DT_PC_WECHAT.getKey(), wechatUser.getMerId());
                        if(device != null){
                            DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                            BeanUtils.copyProperties(device, deviceInfoVo);
                            deviceInfoVoList.add(deviceInfoVo);
                        }
                    }
                }
            }
        }catch (Exception e){

        }

        try {
            //营销数据
            String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
            String marketingRewardId = wechatUser.getId() + "" + wechatUser.getRegSource();
            Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
            MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
            if (marketingRewardVo == null) {
                marketingRewardVo = new MarketingRewardVo(true);
            }
            wechatUserInfoVo.setMarketingReward(marketingRewardVo);

            String marketingRewardsBlackListId = marketingRewardsBlackListService.isInBlackList(wechatUser.getBizUserId(), wechatUser.getMerId());
            wechatUserInfoVo.setMarketingRewardsBlackListId(marketingRewardsBlackListId);
        }catch (Exception e){

        }


        //淘宝SID,默认查询第一条
        TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
        tbUserInfoQuery.setMerId(wechatUser.getMerId());
        tbUserInfoQuery.setUserId(wechatUser.getId());
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(new Page<>(), tbUserInfoQuery);
        if(tbUserInfoList != null && tbUserInfoList.size() > 0){
            wechatUserInfoVo.setSpecialId(tbUserInfoList.get(0).getSpecialId());
        }


        return wechatUserInfoVo;
    }

    /**
     * 根据单个机器人群发消息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserBatchSendMsgDto
     * @return null
     */
    public Integer groupSendMsgByDeviceUniqueId(WechatUserBatchSendMsgDto wechatUserBatchSendMsgDto){
        //记录成功发送总数
        int totalCount_son_succ = 0;

        //群发消息设置
        WechatUserGroupSendMsgDto wechatUserGroupSendMsgDto = wechatUserBatchSendMsgDto.getWechatUserGroupSendMsgDto();
        //查询会员条件
        WechatUserQuery wechatUserQuery = wechatUserBatchSendMsgDto.getWechatUserQuery();
        wechatUserQuery.setMerId(wechatUserBatchSendMsgDto.getMerId());
        if(wechatUserQuery == null){//判断条件是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; wechatUserQuery is null");
            return totalCount_son_succ;
        }
        if(wechatUserQuery.getDeviceUniqueId() == null){//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return totalCount_son_succ;
        }

        //查询数据库当中主任务是否存在
        if(wechatUserBatchSendMsgDto.getGroupSendJobParentId() == null){
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParentId is null");
            return totalCount_son_succ;
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUserQuery.getDeviceUniqueId(), wechatUserBatchSendMsgDto.getMerId());
        if(deviceWechatInfo == null){
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + wechatUserQuery.getDeviceUniqueId());
            return totalCount_son_succ;
        }

        //免打扰时间
        Integer busyTimeInterval = wechatUserGroupSendMsgDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if(busyTimeInterval != null){
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = wechatUserGroupSendMsgDto.getBeginTime() - busyTimeInterval * 3600 ;
            wechatUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询这个机器人的所有会员-根据创建时间来分段查询
        //先查询创建时间最小得会员-然后根据10天内创建时间段来查询所有得会员
        //MinMaxCreateTimeVo minMaxCreateTimeVo = wechatUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
        //查询总数
        Integer count = wechatUserMapper.findCount(wechatUserQuery);
        //有总数
        if(Tools.getInteger(count) != 0){
            int now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(wechatUserBatchSendMsgDto.getGroupSendJobParentId()); //主任务id
            groupSendJob_son.setMerId(wechatUserBatchSendMsgDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wechatUserQuery.getDeviceUniqueId());
            groupSendJob_son.setName(wechatUserGroupSendMsgDto.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.PRIVATE_USER.getId());
            groupSendJob_son.setContent(Tools.getStr(wechatUserGroupSendMsgDto.getContent()));
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(0); //默认消息数为0
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(wechatUserGroupSendMsgDto.getTimeInterval());
            groupSendJob_son.setBeginTime(wechatUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setEndTime(wechatUserGroupSendMsgDto.getEndTime());
            groupSendJob_son.setExptime(now + 15*24*3600); //当前时间之后的15天内
            groupSendJob_son.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserGroupSendMsgDto.getUserLabList())));
            groupSendJob_son.setCleanLab(wechatUserGroupSendMsgDto.getCleanLab());
            groupSendJob_son.setUserRemark(Tools.getStr(wechatUserGroupSendMsgDto.getUserRemark()));
            groupSendJob_son.setNightTime(wechatUserGroupSendMsgDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(wechatUserGroupSendMsgDto.getBusyTimeInterval());
            groupSendJob_son.setSendStartTime(wechatUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setIgnoreName(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserQuery.getNameExcludeList())));
            groupSendJob_son.setIgnoreRemark(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserQuery.getRemarkExcludeList())));
            groupSendJob_son.setParaQueryType(1); //默认创建任务前筛选条件
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {
                //延迟时间
                int delay = 0;//循环累加延迟时间

                //每页个数
                int size = 10;
                if(Tools.getInteger(count) > 0 ){
                    int totalPage = count / size + 1; //总页数
                    for(int i = totalPage ; i>0;  i--){
                        //每个时间段分页查询，每页200个
                        Page<WechatUserSimpleVo> page = new Page<>();
                        page.setCurrent(i);
                        page.setSize(size);
                        List<WechatUserSimpleVo> wechatUserSimpleVoList = wechatUserMapper.findSimpleByList(page, wechatUserQuery);
                        if(wechatUserSimpleVoList != null && wechatUserSimpleVoList.size() > 0){
                            List<NewGroupSendMsgDto> groupSendMsgDtoList = new ArrayList<>();
                            for(WechatUserSimpleVo wechatUserSimpleVo : wechatUserSimpleVoList) {
                                //发送MQ消息
                                NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                                newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                                newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                                String msg = Tools.getStr(groupSendJob_son.getContent());
                                msg = msg.replace("[随机表情]", Tools.getStr(EmojiUtil.getRandomEmoji()))
                                        .replace("[昵称]", Tools.getStr(wechatUserSimpleVo.getNickName()));
                                newGroupSendMsgDto.setMsg(msg);
                                newGroupSendMsgDto.setMerId(wechatUserSimpleVo.getMerId());
                                newGroupSendMsgDto.setDeviceUniqueId(wechatUserSimpleVo.getDeviceUniqueId());
                                newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                                newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                                newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                                newGroupSendMsgDto.setUserId(wechatUserSimpleVo.getId());
                                newGroupSendMsgDto.setBizUserId(wechatUserSimpleVo.getBizUserId());
                                newGroupSendMsgDto.setNickName(wechatUserSimpleVo.getNickName());
                                newGroupSendMsgDto.setDelay(delay);
                                newGroupSendMsgDto.setOriginalDelay(delay);
                                delay = delay + wechatUserGroupSendMsgDto.getTimeInterval(); //循环累加延迟时间
                                newGroupSendMsgDto.setRetry(0);
                                newGroupSendMsgDto.setLabel(groupSendJob_son.getUserLab());
                                newGroupSendMsgDto.setCleanLab(groupSendJob_son.getCleanLab());
                                String remark = Tools.getStr(groupSendJob_son.getUserRemark());
                                remark = remark.replace("[昵称]", Tools.getStr(wechatUserSimpleVo.getNickName()))
                                        .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                newGroupSendMsgDto.setRemark(remark);
                                groupSendMsgDtoList.add(newGroupSendMsgDto);
                            }

                            //群发消息
                            if(groupSendMsgDtoList.size() > 0){
                                UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                                if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                                    totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                    logger.info("----查询结果群发消息调用微服务推送消息---para={}, size={}, result={}", JSONObject.toJSONString(wechatUserQuery),groupSendMsgDtoList.size(),JSONObject.toJSONString(uzaiRespVo));
                                }else{
                                    //失败的在调用一次,再次失败则修改群发消息条数
                                    UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                                    if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200){
                                        logger.info("---查询结果群发消息第二次调用微服务推送消息成功---msg={}", uzaiRespVo_repeat.getMsg());
                                        totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                    }else{
                                        logger.error("---查询结果群发消息第二次调用微服务推送消息---error={}", uzaiRespVo_repeat.getMsg());
                                    }
                                }
                            }
                        }
                    }
                }
            }catch (Exception e){
                logger.error("---个人微信会员群发消息异常---deviceUniqueId={},msg={}", wechatUserQuery.getDeviceUniqueId(), e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(totalCount_son_succ);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return totalCount_son_succ;
    }

    /**
     * (多选框选择会员)根据单个机器人群发消息(异步)
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserSendMsgBatchDto
     * @return null
     */
    public Integer groupSendMsgByDeviceUniqueIdBatch(WechatUserSendMsgBatchDto wechatUserSendMsgBatchDto){

        //记录子任务成功发送总数
        int totalCount_son_succ = 0;

        //查询这个机器人的所有会员
        List<Long> idList = wechatUserSendMsgBatchDto.getIdList();
        if(idList == null || idList.size() == 0){
            logger.error("--groupSendMsgByDeviceUniqueIdBatch is error; idList is null");
            return totalCount_son_succ;
        }

        //获取群发消息任务内容
        WechatUserGroupSendMsgDto wechatUserGroupSendMsgDto = wechatUserSendMsgBatchDto.getWechatUserGroupSendMsgDto();
        wechatUserGroupSendMsgDto.setMerId(wechatUserSendMsgBatchDto.getMerId());
        if(wechatUserGroupSendMsgDto  == null ){
            return totalCount_son_succ;
        }

        if(wechatUserSendMsgBatchDto.getDeviceUniqueId() == null){//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return totalCount_son_succ;
        }

        //查询数据库当中主任务是否存在
        if(wechatUserSendMsgBatchDto.getGroupSendJobParentId() == null){
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParentId is null");
            return totalCount_son_succ;
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUserSendMsgBatchDto.getDeviceUniqueId(), wechatUserSendMsgBatchDto.getMerId());
        if(deviceWechatInfo == null){
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + wechatUserSendMsgBatchDto.getDeviceUniqueId());
            return totalCount_son_succ;
        }

        //封装该机器人下的会员
        List<WechatUser> wechatUserList = new ArrayList<>();
        if(idList != null && idList.size() > 0){
            for(Long id : idList){
                WechatUser wechatUser = wechatUserMapper.selectById(id, wechatUserSendMsgBatchDto.getMerId());
                if(wechatUser.getDeviceUniqueId().longValue() == deviceWechatInfo.getId().longValue()){ //匹配该机器人的用户
                    wechatUserList.add(wechatUser);
                }
            }
        }

        if(wechatUserList != null && wechatUserList.size() > 0){
            Integer now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(wechatUserSendMsgBatchDto.getGroupSendJobParentId()); //主任务id
            groupSendJob_son.setMerId(wechatUserSendMsgBatchDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            groupSendJob_son.setDeviceUniqueId(wechatUserSendMsgBatchDto.getDeviceUniqueId());
            groupSendJob_son.setName(wechatUserGroupSendMsgDto.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.PRIVATE_USER.getId());
            groupSendJob_son.setContent(Tools.getStr(wechatUserGroupSendMsgDto.getContent()));
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(0); //默认发送总数为0
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(wechatUserGroupSendMsgDto.getTimeInterval());
            groupSendJob_son.setBeginTime(wechatUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setEndTime(wechatUserGroupSendMsgDto.getEndTime());
            groupSendJob_son.setExptime(now + 15*24*3600); //当前时间之后的15天内
            groupSendJob_son.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserGroupSendMsgDto.getUserLabList())));
            groupSendJob_son.setCleanLab(wechatUserGroupSendMsgDto.getCleanLab());
            groupSendJob_son.setUserRemark(Tools.getStr(wechatUserGroupSendMsgDto.getUserRemark()));
            groupSendJob_son.setNightTime(wechatUserGroupSendMsgDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(wechatUserGroupSendMsgDto.getBusyTimeInterval());
            groupSendJob_son.setSendStartTime(wechatUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setParaQueryType(1);//默认先筛选条件在创建任务
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            //群发消息
            try {

                //延迟时间
                int delay = 0;//循环累加延迟时间
                //发送消息
                List<NewGroupSendMsgDto> groupSendMsgDtoList = new ArrayList<>();
                for(WechatUser wechatUser : wechatUserList){
                    if(wechatUser != null){
                        //发送MQ消息
                        NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                        newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                        newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                        String msg = Tools.getStr(groupSendJob_son.getContent());
                        msg = msg.replace("[随机表情]",Tools.getStr(EmojiUtil.getRandomEmoji()))
                                .replace("[昵称]",Tools.getStr(wechatUser.getNickName()));
                        newGroupSendMsgDto.setMsg(msg);
                        newGroupSendMsgDto.setMerId(wechatUser.getMerId());
                        newGroupSendMsgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                        newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        newGroupSendMsgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                        newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                        newGroupSendMsgDto.setUserId(wechatUser.getId());
                        newGroupSendMsgDto.setBizUserId(wechatUser.getBizUserId());
                        newGroupSendMsgDto.setNickName(wechatUser.getNickName());
                        newGroupSendMsgDto.setDelay(delay);
                        newGroupSendMsgDto.setOriginalDelay(delay);
                        delay = delay + wechatUserGroupSendMsgDto.getTimeInterval(); //循环累加延迟时间
                        newGroupSendMsgDto.setRetry(0);
                        newGroupSendMsgDto.setLabel(Tools.getStrEmpty(JSONObject.toJSONString(wechatUserGroupSendMsgDto.getUserLabList())));
                        newGroupSendMsgDto.setCleanLab(wechatUserGroupSendMsgDto.getCleanLab());
                        String remark = Tools.getStr(wechatUserGroupSendMsgDto.getUserRemark());
                        remark = remark.replace("[昵称]",Tools.getStr(wechatUser.getNickName()))
                                .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                        newGroupSendMsgDto.setRemark(remark);
                        groupSendMsgDtoList.add(newGroupSendMsgDto);
                    }

                    //大于10个消息就发送一次，发送成功就清空该列表
                    if(groupSendMsgDtoList != null && groupSendMsgDtoList.size() >= 10){
                        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                            logger.info("----手动选择会员群发调用微服务推送消息成功---para={},result={}", JSONObject.toJSONString(groupSendMsgDtoList), JSONObject.toJSONString(uzaiRespVo));
                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                            //清空发送消息
                            groupSendMsgDtoList.clear();
                        }else{
                            //失败的在调用一次,再次失败则修改群发消息条数
                            UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                            if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200){
                                logger.info("----手动选择会员群发第二次调用微服务推送成功---msg={}", uzaiRespVo_repeat.getMsg());
                                totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                //清空发送消息
                                groupSendMsgDtoList.clear();
                            }else{
                                logger.error("----手动选择会员群发第二次调用微服务推送消息失败---error={}", uzaiRespVo_repeat.getMsg());
                            }
                        }
                    }
                }

                //最后在统一发送剩余的消息
                if(groupSendMsgDtoList != null && groupSendMsgDtoList.size() > 0){
                    UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                    if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
                        logger.info("----手动选择会员群发调用微服务推送消息成功---para={},result={}", JSONObject.toJSONString(groupSendMsgDtoList), JSONObject.toJSONString(uzaiRespVo));
                        totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                        //清空发送消息
                        groupSendMsgDtoList.clear();
                    }else{
                        logger.info("----手动选择会员群发第二次调用微服务推送消息---error={}", uzaiRespVo.getMsg());
                        //失败的在调用一次,再次失败则修改群发消息条数
                        UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                        if(uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200){
                            logger.info("----手动选择会员群发第二次调用微服务推送成功---msg={}", uzaiRespVo_repeat.getMsg());
                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                            //清空发送消息
                            groupSendMsgDtoList.clear();
                        }else{
                            logger.error("----手动选择会员群发第二次调用微服务推送消息失败---error={}", uzaiRespVo_repeat.getMsg());
                        }
                    }
                }

            }catch (Exception e){
                logger.error("---个人微信会员群发消息异常---deviceUniqueId={},msg={}", wechatUserSendMsgBatchDto.getDeviceUniqueId(), e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(totalCount_son_succ);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return totalCount_son_succ;
    }

    /**
     * 删除用户信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param id
     * @return null
     */
    public void deleteUserById(Long id, Long merId){
        WechatUser wechatUser = wechatUserMapper.selectById(id, merId);
        if(wechatUser == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //判断是否关联APP，如果关联，不允许删除
        int appUserCount = appUserMapper.countByRelUserId(wechatUser.getId());
        if(appUserCount > 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "此会员关联app，不能删除");
        }

        int now = DateUtil.getNowTime();

        //真删除
        wechatUserMapper.deleteById(id,merId);

        //删除缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.WX_USER_ID.getKey(), merId, wechatUser.getBizUserId()));

        //删除ES
        try{
            //删除会员基本信息
            String uzai_user_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
            String uzai_user_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_INFO, wechatUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_info, uzai_user_info_id);

            //删除会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_ext_info, uzai_user_ext_info_id);

            //删除营销奖励信息
            String uzai_user_marketing_reward_info_id = wechatUser.getId() + "" + wechatUser.getRegSource();
            elasticsearchUtil.deleteDataById(EsIndexName.UZAI_MARKETING_REWARD_INFO, uzai_user_marketing_reward_info_id);

        }catch (Exception e){
            logger.error("删除ES会员扩展信息出现异常:{}"+ e.getMessage());
        }

        //根据此会员的身份来查询下级用户
        if(wechatUser.getIdentity().intValue() == IdentityEnum.BUYER.getId()){ //此会员是买家
            //查询所有下级买家
            WechatUserQuery wechatUserQuery = new WechatUserQuery();
            wechatUserQuery.setMerId(wechatUser.getMerId());
            wechatUserQuery.setParentId(wechatUser.getId());

            //查询总数
            Integer count = wechatUserMapper.findCount(wechatUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<WechatUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                    if(wechatUserList != null && wechatUserList.size() > 0){
                        for(WechatUser wechatUser_son : wechatUserList) {
                            try {
                                //旧上级树
                                String parentInfoOld_Nson = wechatUser_son.getParentInfo();
                                //将此会员的上级清空
                                wechatUser_son.setParentId(0L);
                                wechatUser_son.setParentInfo("");
                                wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                //批量替换清空
                                //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", wechatUser_son.getMerId(), true);
                                wechatUserTreeInfoService.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", wechatUser_son.getMerId(), true);
                                //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", wechatUser_son.getMerId(), false);
                                wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_Nson, "", wechatUser_son.getMerId(), false);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

        }else if(wechatUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()){//代理身份
            //查询所有下级代理
            WechatUserQuery wechatUserQuery = new WechatUserQuery();
            wechatUserQuery.setMerId(wechatUser.getMerId());
            wechatUserQuery.setAgentId(wechatUser.getId());

            //查询总数
            Integer count = wechatUserMapper.findCount(wechatUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<WechatUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                    if(wechatUserList != null && wechatUserList.size() > 0){
                        for(WechatUser wechatUser_son : wechatUserList) {
                            try {
                                //旧代理树
                                String agentInfoOld_Nson = wechatUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                wechatUser_son.setAgentId(0L);
                                wechatUser_son.setAgentInfo("");
                                wechatUser_son.setUpdateTime(DateUtil.getNowTime());
                                wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                //批量替换
                                //wechatUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", wechatUser_son.getMerId(), true);
                                wechatUserTreeInfoService.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", wechatUser_son.getMerId(), true);
                                //wechatUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", wechatUser_son.getMerId(), false);
                                wechatUserTreeInfoService.batchUpdateParentInfo(agentInfoOld_Nson, "", wechatUser_son.getMerId(), false);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

        }else if(wechatUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//合伙人身份
            //查询所有下级代理
            WechatUserQuery wechatUserQuery = new WechatUserQuery();
            wechatUserQuery.setMerId(wechatUser.getMerId());
            wechatUserQuery.setPartnerId(wechatUser.getId());

            //查询总数
            Integer count = wechatUserMapper.findCount(wechatUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<WechatUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                    if(wechatUserList != null && wechatUserList.size() > 0){
                        for(WechatUser wechatUser_son : wechatUserList) {
                            try {
                                //清空合伙人
                                wechatUser_son.setPartnerId(0L);
                                wechatUser_son.setUpdateTime(DateUtil.getNowTime());
                                wechatUserMapper.updateIdentityInfo(wechatUser_son);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", wechatUser.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            MinMaxCreateTimeVo minMaxCreateTimeVo = wechatUserMapper.findMinAndMaxCreateTime(wechatUserQuery);
//            //查询总数
//            Integer count = wechatUserMapper.findCount(wechatUserQuery);
//            //有总数，且最小创建时间有
//            if(minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        wechatUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        wechatUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<WechatUser> wechatUserList = wechatUserMapper.findByList(wechatUserQuery);
//                        if (wechatUserList != null && wechatUserList.size() > 0) {
//                            for (WechatUser wechatUser_son : wechatUserList) {
//                                //清空合伙人
//                                wechatUser_son.setPartnerId(0L);
//                                wechatUserMapper.updateIdentityInfo(wechatUser_son);
//                            }
//                        }
//                    }
//                }
//            }
        }

    }

    /**
     * 删除上下级会员关系
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserDeleteSonDto
     * @return null
     */
    public void deleteSonWechatUser(WechatUserDeleteSonDto wechatUserDeleteSonDto){

        Long merId = wechatUserDeleteSonDto.getMerId();
        Long id = wechatUserDeleteSonDto.getId();
        Integer identity = wechatUserDeleteSonDto.getIdentity();

        if(identity == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "身份参数不能为空");
        }

        WechatUser wechatUser = wechatUserMapper.selectById(id, merId);
        if(wechatUser == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //上级会员
        WechatUser wechatUserParent = null;

        //根据此会员的身份来查询下级用户
        if(identity.intValue() == IdentityEnum.BUYER.getId().intValue()){ //此会员是买家
            Long parentId = wechatUser.getParentId();
            wechatUserParent = wechatUserMapper.selectById(parentId, merId);

            //清理上级买家关系
            wechatUser.setParentId(0L);
            wechatUser.setParentInfo("");
            wechatUser.setUpdateTime(DateUtil.getNowTime());
            wechatUserMapper.updateIdentityInfo(wechatUser);

            //查询所有下级买家
            WechatUserQuery wechatUserQuery = new WechatUserQuery();
            wechatUserQuery.setMerId(wechatUser.getMerId());
            wechatUserQuery.setParentId(wechatUser.getId());

            //查询总数
            Integer count = wechatUserMapper.findCount(wechatUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页10个
                    Page<WechatUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                    if(wechatUserList != null && wechatUserList.size() > 0){
                        for(WechatUser wechatUser_son : wechatUserList) {
                            try {
                                //旧上级树
                                String parentInfoOld_Nson = wechatUser_son.getParentInfo();
                                //将此会员的上级树修改为上级的id
                                wechatUser_son.setParentInfo(String.valueOf(wechatUser.getId()));
                                wechatUser_son.setUpdateTime(DateUtil.getNowTime());
                                wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                //批量替换清空
                                //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, String.valueOf(wechatUser.getId()), wechatUser.getMerId(), false);
                                wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_Nson, String.valueOf(wechatUser.getId()), wechatUser.getMerId(), false);
                            } catch (Exception e) {
                                logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }
        }else if(identity.intValue() == IdentityEnum.AGENT.getId().intValue()){//代理身份

            Long agentId = wechatUser.getAgentId();
            wechatUserParent = wechatUserMapper.selectById(agentId, merId);

            //清理上级代理关系
            wechatUser.setAgentId(0L);
            wechatUser.setAgentInfo("");
            wechatUser.setUpdateTime(DateUtil.getNowTime());
            wechatUserMapper.updateIdentityInfo(wechatUser);

            //查询所有下级代理
            WechatUserQuery wechatUserQuery = new WechatUserQuery();
            wechatUserQuery.setMerId(wechatUser.getMerId());
            wechatUserQuery.setAgentId(wechatUser.getId());

            //查询总数
            Integer count = wechatUserMapper.findCount(wechatUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页10个
                    Page<WechatUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                    if(wechatUserList != null && wechatUserList.size() > 0){
                        for(WechatUser wechatUser_son : wechatUserList) {
                            try {
                                //旧代理树
                                String agentInfoOld_Nson = wechatUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                wechatUser_son.setAgentInfo(String.valueOf(wechatUser.getId()));
                                wechatUser_son.setUpdateTime(DateUtil.getNowTime());
                                wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                //批量替换
                                //wechatUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, String.valueOf(wechatUser.getId()), wechatUser.getMerId(), false);
                                wechatUserTreeInfoService.batchUpdateParentInfo(agentInfoOld_Nson, String.valueOf(wechatUser.getId()), wechatUser.getMerId(), false);
                            } catch (Exception e) {
                                logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }
        }else if(identity.intValue() == IdentityEnum.PARTNER.getId().intValue()){//合伙人

            Long partnerId = wechatUser.getPartnerId();
            wechatUserParent = wechatUserMapper.selectById(partnerId, merId);

            //清理合伙人关系
            wechatUser.setPartnerId(0L);
            wechatUser.setUpdateTime(DateUtil.getNowTime());
            wechatUserMapper.updateIdentityInfo(wechatUser);
        }

        //修改ES缓存
        try{
            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
            //查询会员基本信息
            Map<String,Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id, null);
            if(dataMp_ext != null){
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(wechatUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id);
            }
        }catch (Exception e){
            logger.error("修改会员营销策略信息出现异常:{}"+ e.getMessage());
        }

        //断绝下级关系，发送修改会员敏感信息报警消息
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(wechatUserDeleteSonDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, wechatUserDeleteSonDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        //发送修改会员数据提醒通知
        if(wechatUserParent == null){
            wechatUserParent = new WechatUser();
        }
        StringBuffer content = new StringBuffer("正在删除会员的下级：")
                                    .append(wechatUser.getNickName())
                                    .append("(").append(wechatUser.getWxid()).append(")");
        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content);
        ext.put("nick", wechatUserParent.getNickName());
        ext.put("wxid", wechatUserParent.getBizUserId());
        ext.put("userid", wechatUserParent.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送删除下级关系报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

    }

    /**
     * 分页查询微信用户账户明细列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param userAccDetailQuery
     * @return null
     */
    public Page<UserAccDetailInfoVo> findWechatUserAccDetailList(UserAccDetailQuery userAccDetailQuery){

        //用户ID不能为空，必须指定用户
        if(userAccDetailQuery.getUserId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请指定用户进行查询");
        }

        //新建返回到页面的LIST对象
        List<UserAccDetailInfoVo> wechatUserAccDetailInfoVoList = new ArrayList<UserAccDetailInfoVo>();
        //执行分页查询对象
        Page<UserAccDetail> page = new Page<>();
        userAccDetailQuery.convert(page);
        List<UserAccDetail> userAccDetailList = null;
        if (super.checkStartEndTimeIsHistoryQuery(userAccDetailQuery.getQueryStartTime(), userAccDetailQuery.getQueryEndTime(), userAccDetailQuery.getQueryMonth())) {
            //查询月份不等于空，则判断月份来查询历史数据
            String tableSuffix = null;
            if(StringUtils.isNotBlank(userAccDetailQuery.getQueryMonth())){
                //判断查询月份是否已经是历史数据
                DateTime parse = DateUtil.parse(userAccDetailQuery.getQueryMonth(), "yyyy-MM");
                tableSuffix = parse.toString("yyMM");
            }else if(userAccDetailQuery.getQueryEndTime() != null){
                tableSuffix = DateTime.of(userAccDetailQuery.getQueryEndTime() * 1000L).toString("yyMM");
            }
            UzaiRespVo<Page<UserAccDetail>> listUzaiRespVoRes = historyDataFeignService.searchAccDetail(tableSuffix, userAccDetailQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("提现列表查询失败");
            }
            if(listUzaiRespVoRes.getData() != null){
                userAccDetailList = listUzaiRespVoRes.getData().getRecords();
                page.setTotal(listUzaiRespVoRes.getData().getTotal());
            }
        }
        // 反之查询90天内的订单数据
        else {
            userAccDetailList = userAccDetailMapper.findByList(page, userAccDetailQuery);
        }

        if(userAccDetailList != null){
            for (UserAccDetail wechatUserAccDetail : userAccDetailList){
                UserAccDetailInfoVo wechatUserAccDetailInfoVo = new UserAccDetailInfoVo();
                BeanUtils.copyProperties(wechatUserAccDetail, wechatUserAccDetailInfoVo);
                //用户昵称
                WechatUser wechatUser = wechatUserMapper.selectById(wechatUserAccDetail.getUserId(), userAccDetailQuery.getMerId());
                if(wechatUser != null){
                    wechatUserAccDetailInfoVo.setNickName(wechatUser.getNickName());
                }
                //明细类型
                wechatUserAccDetailInfoVo.setTypeName(AccDetailTypeEnum.getById(wechatUserAccDetail.getType()).getDesc());

                //订单编号商户订单号
                wechatUserAccDetailInfoVo.setOrderIdTradeno(Tools.getStr(wechatUserAccDetail.getOrderId()) + "/" +Tools.getStr(wechatUserAccDetail.getTradeno()));
                wechatUserAccDetailInfoVoList.add(wechatUserAccDetailInfoVo);
            }
        }
        //返回到页面分页对象
        Page<UserAccDetailInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(wechatUserAccDetailInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询用户会员渠道ID列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param tbUserInfoQuery
     * @return null
     */
    public Page<TbUserInfoVo> findTbUserInfoList(TbUserInfoQuery tbUserInfoQuery){
        //新建返回到页面的LIST对象
        List<TbUserInfoVo> tbUserInfoVoList = new ArrayList<TbUserInfoVo>();
        //执行分页查询对象
        Page<TbUserInfo> page = new Page<>();
        tbUserInfoQuery.convert(page);
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(page, tbUserInfoQuery);
        if(tbUserInfoList != null){
            for (TbUserInfo tbUserInfo : tbUserInfoList){
                TbUserInfoVo tbUserInfoVo = new  TbUserInfoVo();
                BeanUtils.copyProperties(tbUserInfo, tbUserInfoVo);
                //用户昵称
                TbToken tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(),0);
                if(tbToken == null){
                    tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(), 1);
                }
                if(tbToken != null){
                    tbUserInfoVo.setTbTokenName(tbToken.getUserName());
                }
                tbUserInfoVoList.add(tbUserInfoVo);
            }
        }
        //返回到页面分页对象
        Page<TbUserInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbUserInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 修改会员渠道ID
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param tbUserInfoUpdateDto
     * @return null
     */
    public void updateTbUserInfo(TbUserInfoUpdateDto tbUserInfoUpdateDto){
        if(tbUserInfoUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        TbUserInfo tbUserInfo = tbUserInfoMapper.selectById(tbUserInfoUpdateDto.getId(), tbUserInfoUpdateDto.getMerId());
        tbUserInfo.setSpecialId(tbUserInfoUpdateDto.getSpecialId());
        tbUserInfo.setRelationId(tbUserInfoUpdateDto.getRelationId());
        tbUserInfo.setUpdateTime(DateUtil.getNowTime());
        tbUserInfoMapper.updateById(tbUserInfo);
    }

    /**
     * 删除会员渠道ID
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param tbUserInfoIdDto
     * @return null
     */
    public void deleteTbUserInfo(TbUserInfoIdDto tbUserInfoIdDto){
        if(tbUserInfoIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        tbUserInfoMapper.deleteById(tbUserInfoIdDto.getId(), tbUserInfoIdDto.getMerId());
    }


    /**
     * 修改微信用户积分余额
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserUpdateBalanceDto
     * @return null
     */
    @Transactional
    public void updateWechatUserBalance(WechatUserUpdateBalanceDto wechatUserUpdateBalanceDto){
        if(wechatUserUpdateBalanceDto.getId() == null || wechatUserUpdateBalanceDto.getBalance() ==null || wechatUserUpdateBalanceDto.getIntegral() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //至少要修改一个
        if(wechatUserUpdateBalanceDto.getBalance() == null && wechatUserUpdateBalanceDto.getIntegral() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分和余额至少要修改一项");
        }

        //修改值不能为负数
        if(Tools.getDouble(wechatUserUpdateBalanceDto.getBalance()).doubleValue() <  0 || Tools.getInteger(wechatUserUpdateBalanceDto.getIntegral()).intValue() < 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能输入大于0的数");
        }

        if(StringUtils.isNotBlank(wechatUserUpdateBalanceDto.getRemark())){
            //判断是否包括表情
            if(EmojiUtil.containsEmoji(wechatUserUpdateBalanceDto.getRemark())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "原因不能包含表情符号");
            }
        }

        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserUpdateBalanceDto.getId(), wechatUserUpdateBalanceDto.getMerId());
        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员余额和积分;");
        //AOP切面，封装操作日志内容
        String aspectOperatorLog = "修改余额积分";

        //变更余额
        Double balance = wechatUserUpdateBalanceDto.getBalance();
        Double changeBalance = 0.0D;
        //表示修改余额
        if(balance != null){
            //修改类型类型
            Integer balanceType = wechatUserUpdateBalanceDto.getBalanceType();
            if(balanceType == null){ //修改余额
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入余额修改类型");
            }
            if(!Lists.newArrayList(-1,0,1).contains(balanceType)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "余额修改类型值有误");
            }

            //旧余额
            Double oldBalance = Tools.getDouble(wechatUser.getBalance());
            //新余额
            Double newBalance = 0.00D;
            if(balanceType.intValue() == -1){ //减量
                //减少
                newBalance = Math.sub(oldBalance, balance);
                changeBalance = Math.sub(0, balance);
                aspectOperatorLog = aspectOperatorLog + "；减少余额:" + balance;
            }else if(balanceType.intValue() == 1){ //增量
                //增加
                newBalance = Math.add(oldBalance, balance);
                changeBalance = balance;
                aspectOperatorLog = aspectOperatorLog + "；增加余额:" + balance;
            }else{//修改成指定值
                newBalance = balance;
                changeBalance = Math.sub(newBalance, oldBalance);
                aspectOperatorLog = aspectOperatorLog + "；修改余额:" + balance;
            }
            wechatUser.setBalance(newBalance);

            content.append("变动余额:" + changeBalance).append(";");
        }


        //表示修改积分
        Integer integral = wechatUserUpdateBalanceDto.getIntegral();
        //变更积分
        Integer changeIntegral = 0;
        if(integral != null) {
            //修改积分类型
            Integer integralType = wechatUserUpdateBalanceDto.getIntegralType();
            if(integralType == null){ //修改积分
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入积分修改类型");
            }
            if(!Lists.newArrayList(-1,0,1).contains(integralType)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分修改类型值有误");
            }

            //旧积分
            Integer oldIntegral = Tools.getInteger(wechatUser.getIntegral());
            //新积分
            Integer newIntegral = 0;

            if(integralType.intValue() == -1){ //减量
                //减少
                newIntegral = oldIntegral - integral;
                changeIntegral = 0 - integral;
                aspectOperatorLog = aspectOperatorLog + "；减少积分:" + integral;
            }else if(integralType.intValue() == 1){ //增量
                //增加
                newIntegral = oldIntegral + integral;
                changeIntegral = integral;
                aspectOperatorLog = aspectOperatorLog + "；增加积分:" + integral;
            }else{//修改成指定值
                newIntegral = integral;
                changeIntegral = newIntegral - oldIntegral;
                aspectOperatorLog = aspectOperatorLog + "；修改积分:" + integral;
            }

            wechatUser.setIntegral(newIntegral);
            content.append("变动积分:" + changeIntegral).append(";");
        }

        Integer nowTime = DateUtil.getNowTime();
        wechatUser.setUpdateTime(nowTime);
        int j = wechatUserMapper.updateBalance(wechatUser);
        if (j != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //增加账号入账明细
        UserAccDetail wechatUserAccDetail = new UserAccDetail();
        wechatUserAccDetail.setId(IdWorker.getId());
        wechatUserAccDetail.setMerId(wechatUser.getMerId());
        wechatUserAccDetail.setUserId(wechatUser.getId());
        wechatUserAccDetail.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
        wechatUserAccDetail.setDeviceType(wechatUser.getDeviceType());
        wechatUserAccDetail.setChangeInte(changeIntegral);
        wechatUserAccDetail.setChangeBal(changeBalance);
        wechatUserAccDetail.setNewBal(wechatUser.getBalance());
        wechatUserAccDetail.setNewInte(wechatUser.getIntegral());
        wechatUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
        wechatUserAccDetail.setRemark(wechatUserUpdateBalanceDto.getRemark());
        wechatUserAccDetail.setCreateTime(nowTime);
        wechatUserAccDetail.setUpdateTime(nowTime);
        //插入用户账户明细记录
        int insert = userAccDetailMapper.insert(wechatUserAccDetail);
        if(insert!=1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
        }

        //AOP切面，封装操作日志内容
        wechatUserUpdateBalanceDto.setAspectOperatorLog(aspectOperatorLog);

        //发送异常报警通知-修改会员敏感信息
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(wechatUserUpdateBalanceDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员余额和积分
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, wechatUserUpdateBalanceDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        if(loginVo == null){
            loginVo = new LoginVo();
        }
        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content.toString());
        ext.put("nick", wechatUser.getNickName());
        ext.put("wxid", wechatUser.getBizUserId());
        ext.put("userid", wechatUser.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

    }

    /**
     * 修改微信用户定向比例
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserUpdatePriRewardRulesDto
     * @return null
     */
    public void updateWechatUserPriRewardRules(WechatUserUpdatePriRewardRulesDto wechatUserUpdatePriRewardRulesDto){
        if(wechatUserUpdatePriRewardRulesDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserUpdatePriRewardRulesDto.getId(), wechatUserUpdatePriRewardRulesDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取设置定向规则JSON对象
        Map<String,PriRewardRulesDto> priRewardRules = JSONObject.parseObject(wechatUser.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>(){});
        if(priRewardRules == null){
            priRewardRules = new HashMap<>();
        }

        //获取该运营商开启的产品模块
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(wechatUserUpdatePriRewardRulesDto.getMerId(), MerConfigKeyEnum.PRODUCT_SWITCH.getValue());
        if(merBaseConfig != null){
            //获取该运营商开启的产品模块
            List<String> productKeyList = JSONObject.parseArray(merBaseConfig.getVal(), String.class);
            if(productKeyList != null && productKeyList.size() > 0){
                //是否包含淘宝
                if(productKeyList.contains(ProductKeyEnum.TB.getValue())){
                    PriRewardRulesDto tbRule = wechatUserUpdatePriRewardRulesDto.getTbRule();
//                    if(tbRule != null){
//                        Long priRuleId = tbRule.getPriRuleId();
//                        if(priRuleId == null){
//                            tbRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("tbRule", tbRule);
                }

                //是否包含京东
                if(productKeyList.contains(ProductKeyEnum.JD.getValue())){
                    PriRewardRulesDto jdRule = wechatUserUpdatePriRewardRulesDto.getJdRule();
//                    if(jdRule != null){
//                        Long priRuleId = jdRule.getPriRuleId();
//                        if(priRuleId == null){
//                            jdRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("jdRule",jdRule);
                }

                //是否包含拼多多
                if(productKeyList.contains(ProductKeyEnum.PDD.getValue())){
                    PriRewardRulesDto pddRule = wechatUserUpdatePriRewardRulesDto.getPddRule();
//                    if(pddRule != null){
//                        Long priRuleId = pddRule.getPriRuleId();
//                        if(priRuleId == null){
//                            pddRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("pddRule",pddRule);
                }

                //是否包含唯品会
                if(productKeyList.contains(ProductKeyEnum.VPH.getValue())){
                    PriRewardRulesDto vphRule = wechatUserUpdatePriRewardRulesDto.getVphRule();
//                    if(vphRule != null){
//                        Long priRuleId = vphRule.getPriRuleId();
//                        if(priRuleId == null){
//                            vphRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("vphRule",vphRule);
                }

                //是否包含本地生活
                if(productKeyList.contains(ProductKeyEnum.LOCAL_LIVE.getValue())){
                    PriRewardRulesDto localLiveRule = wechatUserUpdatePriRewardRulesDto.getLocalLiveRule();
//                    if(localLiveRule != null){
//                        Long priRuleId = localLiveRule.getPriRuleId();
//                        if(priRuleId == null){
//                            localLiveRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("localLiveRule",localLiveRule);
                }

                //是否包含抖音
                if(productKeyList.contains(ProductKeyEnum.DY.getValue())){
                    PriRewardRulesDto dyRule = wechatUserUpdatePriRewardRulesDto.getDyRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("dyRule", dyRule);
                }

                //是否包含快手
                if(productKeyList.contains(ProductKeyEnum.KS.getValue())){
                    PriRewardRulesDto ksRule = wechatUserUpdatePriRewardRulesDto.getKsRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("ksRule", ksRule);
                }
            }
        }

        wechatUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRules)));
        wechatUser.setUpdateTime(DateUtil.getNowTime());

        wechatUserMapper.updateByIdSelective(wechatUser);


        //修改ES
        try{
            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
            //查询会员基本信息
            Map<String,Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id, null);
            if(dataMp_ext != null){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("priRewardRules", Tools.getStr(wechatUser.getPriRewardRules()));  //修改定向比例
                jsonObject.put("updateTime", DateUtil.getNowTime());

                elasticsearchUtil.updateDataById(jsonObject, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        }catch (Exception e){
            logger.error("删除ES会员扩展信息出现异常:{}"+ e.getMessage());
        }

    }

    /**
     * 修改微信用户会员标签
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param userUpdateMarketingTagDto
     * @return null
     */
    public void updateSysTags(UserUpdateMarketingTagDto userUpdateMarketingTagDto){
        if(userUpdateMarketingTagDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
        }
        WechatUser wechatUser = wechatUserMapper.selectById(userUpdateMarketingTagDto.getId(), userUpdateMarketingTagDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信会员不存在");
        }

        wechatUser.setSysTags(Tools.getStrEmpty(JSONObject.toJSONString(userUpdateMarketingTagDto.getSysTagList())));

        wechatUserMapper.updateSysTags(wechatUser);

    }

    /**
     * 加入黑名单
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserAddBlackDto
     * @return null
     */
    public void addBlackUser(WechatUserAddBlackDto wechatUserAddBlackDto){
        if(wechatUserAddBlackDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserAddBlackDto.getId(), wechatUserAddBlackDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员不存在");
        }

        Integer now = DateUtil.getNowTime();

        //查询是否已经在黑名单当中
        //id为merId_wxid
        String id = wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
        WechatBlacklistPrv wechatBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
        if(wechatBlacklistPrv != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在黑名单中");
        }
        //添加到全网黑名单
        if(wechatUserAddBlackDto.getAllBackFlag() != null && wechatUserAddBlackDto.getAllBackFlag().intValue() == 1){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatUser.getBizUserId(), null);
            WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
            if(wechatBlacklistPub != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在共享黑名单里");
            }
        }

        if(wechatBlacklistPrv == null){
            wechatBlacklistPrv = new WechatBlacklistPrv();
            wechatBlacklistPrv.setId(id);
            wechatBlacklistPrv.setMerId(wechatUser.getMerId());
            wechatBlacklistPrv.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
            wechatBlacklistPrv.setDeviceType(wechatUser.getDeviceType());
            wechatBlacklistPrv.setWxid(wechatUser.getBizUserId());
            wechatBlacklistPrv.setNickName(wechatUser.getNickName());
            wechatBlacklistPrv.setHeadImg(wechatUser.getHeadImg());
            wechatBlacklistPrv.setType(wechatUserAddBlackDto.getUserBlackType());
            wechatBlacklistPrv.setCreateTime(now);
            wechatBlacklistPrv.setRemark(wechatUserAddBlackDto.getRemark());
            wechatBlacklistPrv.setUpdateTime(now);
            elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);

            //添加到全网黑名单
            if(wechatUserAddBlackDto.getAllBackFlag() != null && wechatUserAddBlackDto.getAllBackFlag().intValue() == 1){
                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if(wechatBlacklistPub == null){
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(wechatUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(now);
                    wechatBlacklistPub.setUpdateTime(now);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatUser.getBizUserId());
                }
            }
        }

        //修改会员备注、通讯录备注、发送修改微信终端修改配置指令
        if(Tools.getInteger(wechatUserAddBlackDto.getUpdateRemarkFlag()).intValue() ==1  && StringUtils.isNotBlank(wechatUserAddBlackDto.getRemark())){
            wechatUser.setRemark(wechatUserAddBlackDto.getRemark());
            userOperatorService.updateRemarkByUserAndContacts(wechatUser);
        }

        try {
            //延迟0.5秒
            Thread.sleep(500);
        }catch (Exception e){

        }

    }

    /**
     * 修改微信用户详情信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserInfoUpdateDto
     * @return null
     */
    public void updateWechatUserInfo(WechatUserInfoUpdateDto wechatUserInfoUpdateDto){

        if(wechatUserInfoUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserInfoUpdateDto.getId(), wechatUserInfoUpdateDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取运营商ID
        Long merId = wechatUser.getMerId();
        //用户Id
        Long id = wechatUser.getId();

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员信息;");

        //微信昵称
        if(!Tools.getStr(wechatUserInfoUpdateDto.getNickName()).equals(Tools.getStr(wechatUser.getNickName()))){
            wechatUser.setNickName(Tools.getStr(wechatUserInfoUpdateDto.getNickName()));
        }

        //会员类型
        if(wechatUserInfoUpdateDto.getUserType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不能为空");
        }
        UserType userType = userTypeMapper.selectById(wechatUserInfoUpdateDto.getUserType(), wechatUser.getMerId());
        if(userType == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不存在或已删除");
        }

        //会员类型
        if(Tools.getLong(wechatUserInfoUpdateDto.getUserType()).longValue() != Tools.getLong(wechatUser.getUserType()).longValue()){
            wechatUser.setUserType(wechatUserInfoUpdateDto.getUserType());
            content.append("新会员类型:" + userType.getName()).append(";");
        }

        //支付宝姓名
        Boolean updateAlipayInfoFlag = false;
        if(!Tools.getStr(wechatUserInfoUpdateDto.getAlipayName()).equals(Tools.getStr(wechatUser.getAlipayName()))){
            wechatUser.setAlipayName(wechatUserInfoUpdateDto.getAlipayName());
            updateAlipayInfoFlag = true;
        }

        //支付宝账号
        if(!Tools.getStr(wechatUserInfoUpdateDto.getAlipayAccount()).equals(Tools.getStr(wechatUser.getAlipayAccount()))){
            wechatUser.setAlipayAccount(wechatUserInfoUpdateDto.getAlipayAccount());
            updateAlipayInfoFlag = true;
        }

        //淘宝订单尾号
        if(Tools.getInteger(wechatUserInfoUpdateDto.getTbLastOrderNo()).intValue() != Tools.getInteger(wechatUser.getTbLastOrderNo()).intValue()){
            wechatUser.setTbLastOrderNo(Tools.getInteger(wechatUserInfoUpdateDto.getTbLastOrderNo()));
        }

        //最后下单时间
        if(Tools.getInteger(wechatUserInfoUpdateDto.getLastOrderTime()).intValue() != Tools.getInteger(wechatUser.getLastOrderTime()).intValue()){
            wechatUser.setLastOrderTime(Tools.getInteger(wechatUserInfoUpdateDto.getLastOrderTime()));
        }

        //机器人ID
        if(Tools.getLong(wechatUserInfoUpdateDto.getDeviceUniqueId()).longValue() != Tools.getLong(wechatUser.getDeviceUniqueId()).longValue()){

            //需要验证新机器人和旧机器人是否在同一个会员类型组
            DeviceWechatInfo deviceWechatInfo_new = deviceWechatInfoMapper.selectById(wechatUserInfoUpdateDto.getDeviceUniqueId(), wechatUserInfoUpdateDto.getMerId());
            if(deviceWechatInfo_new == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人不存在");
            }

            ConfigPlan configPlan = configPlanMapper.selectById(deviceWechatInfo_new.getConfigId(), deviceWechatInfo_new.getMerId());
            if(configPlan == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人的配置方案不存在");
            }

            if(Tools.getLong(configPlan.getUserTypeGroupId()).longValue() == 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人的配置方案还未配置会员类型组");
            }

            //验证会员所在会员类型组是否跟新选组机器人所在配置方案里配置的会员类型组是否一样，如果不一样，则不能修改
            if(Tools.getLong(userType.getGroupId()).longValue() != Tools.getLong(configPlan.getUserTypeGroupId()).longValue()){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新选择的机器人配置的会员类型组与会员的类型组不一样，不能修改");
            }

            wechatUser.setDeviceUniqueId(wechatUserInfoUpdateDto.getDeviceUniqueId());
            content.append("新机器人唯一id:" + Tools.getLong(wechatUserInfoUpdateDto.getDeviceUniqueId())).append(";");
        }

        //系统标签
        List<String> addTagsList = wechatUserInfoUpdateDto.getTagsArr();
        String tagsStr = Tools.getStrEmpty(JSONObject.toJSONString(addTagsList));
        if(!tagsStr.equals(Tools.getStrEmpty(wechatUser.getTags()))){
            wechatUser.setTags(tagsStr);
        }

        //会员标签
        List<SysTagVo> sysTagsList = wechatUserInfoUpdateDto.getSysTagsList();
        String sysTagsStr = Tools.getStrEmpty(JSONObject.toJSONString(sysTagsList));
        if(!sysTagsStr.equals(Tools.getStrEmpty(wechatUser.getSysTags()))){
            wechatUser.setSysTags(sysTagsStr);
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        if(!Tools.getStr(wechatUserInfoUpdateDto.getRemark()).equals(Tools.getStr(wechatUser.getRemark()))){ //修改了备注
            //备注
            wechatUser.setRemark(wechatUserInfoUpdateDto.getRemark());
            setRemarkFlag = true;
        }

        //身份
        if(wechatUserInfoUpdateDto.getIdentity() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "身份不能为空");
        }

        if(userType.getIdentity().intValue() != wechatUserInfoUpdateDto.getIdentity().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的会员类型与会员身份不一样");
        }

        //是否修改身份证标志
        boolean flag_identity = false;
        //旧身份
        int identityOld = wechatUser.getIdentity().intValue();
        //新身份
        int identityNew = wechatUserInfoUpdateDto.getIdentity().intValue();

        //旧上级买家
        long parentIdOld = Tools.getLong(wechatUser.getParentId()).longValue();

        //旧代理
        long agentIdOld = Tools.getLong(wechatUser.getAgentId()).longValue();

        //旧合伙人
        long partnerIdOld = Tools.getLong(wechatUser.getPartnerId()).longValue();

        //旧身份自己买家树
        String parentInfoOld_wo = Tools.getStr(wechatUser.getParentInfo());

        //旧身份的所有下级的上级买家树
        String parentInfoOld_son = null;
        if(parentIdOld != 0){
            parentInfoOld_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", parentInfoOld_wo);
        }else{
            parentInfoOld_son = String.valueOf(wechatUser.getId());
        }

        //旧身份自己的代理树
        String agentInfoOld_wo = Tools.getStr(wechatUser.getAgentInfo());

        //旧身份的下级的代理树
        String agentInfoOld_son = null;
        if(agentIdOld != 0){
            agentInfoOld_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", agentInfoOld_wo);
        }else{
            agentInfoOld_son = String.valueOf(wechatUser.getId());
        }

        //如果新身份是合伙人:合伙人、代理、上级买家全部清空
        if(identityNew == IdentityEnum.PARTNER.getId()){
            wechatUserInfoUpdateDto.setPartnerId(0L); //修改合伙人
            wechatUserInfoUpdateDto.setAgentId(0L); //修改代理
            wechatUserInfoUpdateDto.setParentId(0L); //修改上级买家
        }else if(identityNew == IdentityEnum.AGENT.getId()){ //如果新身份是代理:上级买家清空
            wechatUserInfoUpdateDto.setParentId(0L);
        }

        //判断是否修改了身份
        if(identityNew != identityOld){ //修改身份
            flag_identity = true;       //修改身份标志为true
            wechatUser.setIdentity(identityNew); //修改身份属性值
            content.append("新身份:" + IdentityEnum.getById(identityNew).getDesc()).append(";");
        }

        //新上级买家
        long parentIdNew = Tools.getLong(wechatUserInfoUpdateDto.getParentId()).longValue();

        //新代理
        long agentIdNew = Tools.getLong(wechatUserInfoUpdateDto.getAgentId()).longValue();

        //新合伙人
        long partnerIdNew = Tools.getLong(wechatUserInfoUpdateDto.getPartnerId()).longValue();

        //验证合伙人ID是否为合伙人
        boolean flag_partner = false;
        if(partnerIdNew != partnerIdOld){ //修改了合伙人
            //标志合伙人已经修改
            flag_partner = true;
            wechatUser.setPartnerId(partnerIdNew); //修改自己的合伙人信息

            //选择了合伙人，验证对方身份
            if(partnerIdNew != 0 ){
                WechatUser wechatUserPartner_new = wechatUserMapper.selectById(partnerIdNew, wechatUserInfoUpdateDto.getMerId());
                //判断存不存在
                if(wechatUserPartner_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if(wechatUserPartner_new.getIdentity() == null || wechatUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if(wechatUserPartner_new.getId().longValue() == wechatUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
                content.append("新合伙人:" + partnerIdNew).append(";");
            }else{
                content.append("清空合伙人").append(";");
            }
        }

        //验证上级会员ID是否为买家
        boolean flag_parent = false;
        String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
        String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的
        if(parentIdNew != parentIdOld){//修改了上级买家
            //标志上级买家已经修改
            flag_parent = true;
            //修改上级买家ID
            wechatUser.setParentId(parentIdNew);

            //验收上级买家
            if(parentIdNew != 0){ //选择了上级买家
                WechatUser wechatUserParent_new = wechatUserMapper.selectById(parentIdNew, wechatUserInfoUpdateDto.getMerId());
                //判断存不存在
                if(wechatUserParent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }
                //判断身份
                if(wechatUserParent_new.getIdentity() == null || wechatUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if(wechatUserParent_new.getId().longValue() == wechatUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(wechatUserParent_new.getParentInfo());
                if(parentInfo.contains(String.valueOf(wechatUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }
                //判断新上级买家是否有上级买家，
                if(Tools.getLong(wechatUserParent_new.getParentId()).longValue() != 0){//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(wechatUserParent_new.getId()), "_", wechatUserParent_new.getParentInfo());
                    wechatUser.setParentInfo(parentInfoNew_wo);
                }else{
                    parentInfoNew_wo = String.valueOf(wechatUserParent_new.getId());
                    wechatUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", parentInfoNew_wo);

                content.append("新上级:" + parentIdNew).append(";");

            }else{ //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                wechatUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(wechatUser.getId());

                content.append("清空上级").append(";");
            }
        }

        //验证代理身份是否为代理人
        boolean flag_agent = false;
        String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
        String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的
        if(agentIdNew != agentIdOld){ //表示修改了上级代理
            //标志上级代理已经修改
            flag_agent = true;
            //修改代理属性
            wechatUser.setAgentId(agentIdNew);

            if(agentIdNew != 0 ){ //选择了上级代理，需要验证身份
                WechatUser wechatUserAgent_new = wechatUserMapper.selectById(agentIdNew, wechatUserInfoUpdateDto.getMerId());
                //判断存不存在
                if(wechatUserAgent_new == null){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if(wechatUserAgent_new.getIdentity() == null || wechatUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if(wechatUserAgent_new.getId().longValue() == wechatUser.getId().longValue()){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(wechatUserAgent_new.getAgentInfo());
                if(agentInfo.contains(String.valueOf(wechatUser.getId()))){
                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if(Tools.getLong(wechatUserAgent_new.getAgentId()) != 0){ //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(wechatUserAgent_new.getId()), "_", wechatUserAgent_new.getAgentInfo());
                    wechatUser.setAgentInfo(agentInfoNew_wo);
                }else{
                    agentInfoNew_wo = String.valueOf(wechatUserAgent_new.getId());
                    wechatUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(wechatUser.getId()), "_", agentInfoNew_wo);

                content.append("新代理:" + agentIdNew).append(";");

            }else{ //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                wechatUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(wechatUser.getId());
                content.append("清空代理").append(";");
            }
        }

        //修改微信用户详情信息
        int now = DateUtil.getNowTime();
        wechatUser.setUpdateTime(now);
        wechatUserMapper.updateById(wechatUser);

        //修改身份，改变了其他用户的树
        if(flag_identity){
            //判断旧身份类型
            if(identityOld == IdentityEnum.BUYER.getId()){ // 旧身份是买家
                //判断新身份
                if(identityNew == IdentityEnum.AGENT.getId()){ //新身份是代理

                    /**买家转代理-身份往上升
                     * 1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                     * 2: 修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                    //wechatUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfoNew_son, merId);
                    //将上面批量修改SQL语句拆分成单个会员修改
                    wechatUserTreeInfoService.batchUpdateAgentInfoFromParentInfo(id, agentInfoNew_son, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    wechatUserTreeInfoService.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    wechatUserQuery.setMerId(merId);
                    wechatUserQuery.setParentId(id);
                    //查询总数
                    Integer count = wechatUserMapper.findCount(wechatUserQuery);
                    //每页个数
                    int size = 10;
                    if(Tools.getInteger(count) > 0 ){
                        int totalPage = count / size + 1; //总页数
                        for(int i = totalPage ; i>0;  i--){
                            //每个时间段分页查询，每页10个
                            Page<WechatUser> page = new Page<>();
                            page.setCurrent(i);
                            page.setSize(size);
                            List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                            if(wechatUserList != null && wechatUserList.size() > 0){
                                for(WechatUser wechatUser_son : wechatUserList) {
                                    try {
                                        wechatUser_son.setParentId(0L);   //清空上级
                                        wechatUser_son.setParentInfo(""); //清空上级树
                                        wechatUser_son.setAgentId(id);    //修改代理
                                        wechatUser_son.setAgentInfo(agentInfoNew_son); //修改代理树
                                        wechatUser_son.setUpdateTime(now);
                                        wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                        //4:将下N级代理和下N级代理的树更新
                                        String agentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                        String agentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        wechatUserTreeInfoService.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                        wechatUserTreeInfoService.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    } catch (Exception e) {
                                        logger.error("-------batchUpdateAgentInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }else if(identityNew == IdentityEnum.PARTNER.getId()){ //新身份是合伙人

                    /**买家转合伙人-身份往上升
                     * 1: 批量将下N级无合伙人的用户合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无合伙人的合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                    wechatUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    wechatUserTreeInfoService.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    wechatUserQuery.setMerId(merId);
                    wechatUserQuery.setParentId(id);

                    //查询总数
                    Integer count = wechatUserMapper.findCount(wechatUserQuery);
                    //每页个数
                    int size = 10;
                    if(Tools.getInteger(count) > 0 ){
                        int totalPage = count / size + 1; //总页数
                        for(int i = totalPage ; i>0;  i--){
                            //每个时间段分页查询，每页200个
                            Page<WechatUser> page = new Page<>();
                            page.setCurrent(i);
                            page.setSize(size);
                            List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                            if(wechatUserList != null && wechatUserList.size() > 0){
                                for(WechatUser wechatUser_son : wechatUserList) {
                                    try {
                                        wechatUser_son.setParentId(0L);   //清空上级
                                        wechatUser_son.setParentInfo(""); //清空上级树
                                        wechatUser_son.setPartnerId(id);    //修改合伙人
                                        wechatUser_son.setUpdateTime(now);
                                        wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                    } catch (Exception e) {
                                        logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }
            }else if(identityOld == IdentityEnum.AGENT.getId()){ //旧身份是代理
                //判断新身份
                if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                    /**代理转买家-身份往下降
                     *  1：修改下N级代理树(摘除此代理)
                     *  2: 修改下级代理代理信息（代理的代理）、买家信息
                     */

                    //2:修改下N级代理树
                    //分俩次替换（避免替换留下"_"符合）
                    //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_wo, merId, true);
                    wechatUserTreeInfoService.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_wo, merId, true);
                    //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_wo, merId, false);
                    wechatUserTreeInfoService.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_wo, merId, false);

                    //3: 修改下级的代理和代理树
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    wechatUserQuery.setMerId(merId);
                    wechatUserQuery.setAgentId(id);

                    //查询总数
                    Integer count = wechatUserMapper.findCount(wechatUserQuery);
                    //每页个数
                    int size = 10;
                    if(Tools.getInteger(count) > 0 ){
                        int totalPage = count / size + 1; //总页数
                        for(int i = totalPage ; i>0;  i--){
                            //每个时间段分页查询，每页200个
                            Page<WechatUser> page = new Page<>();
                            page.setCurrent(i);
                            page.setSize(size);
                            List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                            if(wechatUserList != null && wechatUserList.size() > 0){
                                for(WechatUser wechatUser_son : wechatUserList) {
                                    try {
                                        wechatUser_son.setAgentId(agentIdNew);           // 修改新的上级代理
                                        wechatUser_son.setAgentInfo(agentInfoNew_wo);    //修改新的代理树
                                        wechatUser_son.setUpdateTime(now);
                                        //买家为空，且身份是买家
                                        if(wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                            wechatUser_son.setParentId(id);                  //修改上级
                                            wechatUser_son.setParentInfo(parentInfoNew_son); //修改上级树
                                            wechatUser_son.setUpdateTime(now);
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                            String parentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            wechatUserTreeInfoService.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                            wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }

                                        wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                    } catch (Exception e) {
                                        logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }else if(identityNew == IdentityEnum.PARTNER.getId()){ //新身份是合伙人

                    /**代理转合伙人-身份往上升
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无合伙人的会员，将合伙人设置为此Id，满足条件:A:代理树包含此ID，B:合伙人为空；
                    wechatUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);
                    //2:修改下N级代理树(清空截断）
                    //分俩次替换（避免替换留下"_"符合）
                    //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "", merId, true);
                    wechatUserTreeInfoService.batchUpdateAgentInfo("_" + agentInfoOld_son, "", merId, true);
                    //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_son, "", merId, false);
                    wechatUserTreeInfoService.batchUpdateAgentInfo(agentInfoOld_son, "", merId, false);
                    //3: 修改下级的代理和代理树
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    wechatUserQuery.setMerId(merId);
                    wechatUserQuery.setAgentId(id);
                    //查询总数
                    Integer count = wechatUserMapper.findCount(wechatUserQuery);
                    //每页个数
                    int size = 10;
                    if(Tools.getInteger(count) > 0 ){
                        int totalPage = count / size + 1; //总页数
                        for(int i = totalPage ; i>0;  i--){
                            //每个时间段分页查询，每页200个
                            Page<WechatUser> page = new Page<>();
                            page.setCurrent(i);
                            page.setSize(size);
                            List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                            if(wechatUserList != null && wechatUserList.size() > 0){
                                for(WechatUser wechatUser_son : wechatUserList) {
                                    try {
                                        wechatUser_son.setAgentId(0L);                    // 清空代理人
                                        wechatUser_son.setAgentInfo("");                  //清空代理人信息
                                        wechatUser_son.setPartnerId(id);                  //修改合伙人
                                        wechatUser_son.setUpdateTime(now);
                                        wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                    } catch (Exception e) {
                                        logger.error("-------updateIdentityInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }
            }else{ //旧身份是合伙人
                //判断新身份
                if(identityNew == IdentityEnum.BUYER.getId()){ //新身份是买家

                    /**合伙人转买家-身份往下降
                     *  1：清空下N合伙人信息,更新买家信息（上级不能为空，代理不能为空，且身份是买家）
                     */
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    wechatUserQuery.setMerId(merId);
                    wechatUserQuery.setPartnerId(id);
                    //查询总数
                    Integer count = wechatUserMapper.findCount(wechatUserQuery);
                    //每页个数
                    int size = 10;
                    if(Tools.getInteger(count) > 0 ){
                        int totalPage = count / size + 1; //总页数
                        for(int i = totalPage ; i>0;  i--){
                            //每个时间段分页查询，每页200个
                            Page<WechatUser> page = new Page<>();
                            page.setCurrent(i);
                            page.setSize(size);
                            List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                            if(wechatUserList != null && wechatUserList.size() > 0){
                                for(WechatUser wechatUser_son : wechatUserList) {
                                    try {
                                        wechatUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是买家
                                        if(wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getAgentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()){
                                            wechatUser_son.setParentId(id);                   //修改上级
                                            wechatUser_son.setParentInfo(parentInfoNew_son);  //修改上级树
                                            wechatUser_son.setUpdateTime(now);
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                            String parentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            wechatUserTreeInfoService.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                            wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }
                                        wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                    } catch (Exception e) {
                                        logger.error("-------batchUpdateParentInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }else if(identityNew == IdentityEnum.AGENT.getId()){ //新身份是代理

                    /**合伙人转代理-身份往下降
                     *  1：清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //wechatUserMapper.batchUpdateAgentInfoFromPartnerIdAndAgentIdNull(id, parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    WechatUserQuery wechatUserQuery = new WechatUserQuery();
                    wechatUserQuery.setMerId(merId);
                    wechatUserQuery.setPartnerId(id);

                    //查询总数
                    Integer count = wechatUserMapper.findCount(wechatUserQuery);
                    //每页个数
                    int size = 10;
                    if(Tools.getInteger(count) > 0 ){
                        int totalPage = count / size + 1; //总页数
                        for(int i = totalPage ; i>0;  i--){
                            //每个时间段分页查询，每页200个
                            Page<WechatUser> page = new Page<>();
                            page.setCurrent(i);
                            page.setSize(size);
                            List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                            if(wechatUserList != null && wechatUserList.size() > 0){
                                for(WechatUser wechatUser_son : wechatUserList) {
                                    try {
                                        wechatUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是代理
                                        if(wechatUser_son.getParentId().longValue() == 0L && wechatUser_son.getAgentId().longValue() == 0L && wechatUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()){
                                            wechatUser_son.setAgentId(id);                   //修改代理
                                            wechatUser_son.setAgentInfo(agentInfoNew_son);  //修改代理树
                                            wechatUser_son.setUpdateTime(now);
                                            //将下N级代理和下N级的代理树更新
                                            String agentInfoOld_Nson = String.valueOf(wechatUser_son.getId());
                                            String agentInfoNew_Nson = wechatUser_son.getId() + "_" + wechatUser_son.getAgentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                            wechatUserTreeInfoService.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                            //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                            wechatUserTreeInfoService.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                        }

                                        wechatUserMapper.updateIdentityInfo(wechatUser_son);
                                    } catch (Exception e) {
                                        logger.error("-------batchUpdateParentInfo is error userId={}, error={}", wechatUser_son.getId(), e.getMessage());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


        //如果修改了上级买家,批量修改下N级买家树
        if(flag_parent){
            //分俩次替换（避免替换留下"_"符合）
            //wechatUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            wechatUserTreeInfoService.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            //wechatUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
            wechatUserTreeInfoService.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
        }

        //如果修改了代理,批量修改下N级代理树
        if(flag_agent){
            //分俩次替换（避免替换留下"_"符合）
            //wechatUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId,  true);
            wechatUserTreeInfoService.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId,  true);
            //wechatUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
            wechatUserTreeInfoService.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
        }

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if(setRemarkFlag){
            //查询机器人
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), merId);
            if(deviceWechatInfo != null){
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setMerId(wechatUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wechatUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(wechatUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }

        //是否修改了支付宝账号和姓名
        if(updateAlipayInfoFlag){
            AlipayUserAuthDto alipayUserAuthDto = new AlipayUserAuthDto();
            alipayUserAuthDto.setAlipayUserId(wechatUser.getAlipayAccount());
            alipayUserAuthDto.setAlipayUserName(wechatUser.getAlipayName());
            alipayUserAuthDto.setUserId(String.valueOf(wechatUser.getId()));
            //获取该会员的appid配置1-获取默认机器人;2-获取机器人的配置方案；3-从配置方案的提现配置里获取appid
            if(wechatUser.getDeviceUniqueId() != null){
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), wechatUser.getMerId());
                if(deviceWechatInfo != null && deviceWechatInfo.getConfigId() != null){
                    ConfigPlan configPlan = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
                    if(configPlan != null && configPlan.getUserTakeBalId() != null){
                        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
                        if(sysPlugin != null && StringUtils.isNotBlank(sysPlugin.getData())){
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                String zf_app_id = jsonObject.getString("zf_app_id");//账房appId
                                if(StringUtils.isNotBlank(zf_app_id)){
                                    alipayUserAuthDto.setAppId(zf_app_id);
                                    UzaiRespVo<Object> objectUzaiRespVo = uzaiCashierServerFeignService.alipayUserAuth(alipayUserAuthDto);
                                    logger.info("--调用账房授权支付宝账号信息微服务接口--para={},result={}", JSONObject.toJSONString(alipayUserAuthDto), JSONObject.toJSONString(objectUzaiRespVo));
                                }
                            }catch (Exception e){
                                logger.error("---配置方案的提现设置插件格式有问题---sysPluginId={}, configId={}, merId={}", sysPlugin.getId(), configPlan.getId(), configPlan.getMerId());
                            }
                        }
                    }
                }
            }
        }

        //发送异常报警通知-修改会员敏感信息
        if(StringUtils.isNotBlank(content)){
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(wechatUserInfoUpdateDto.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, wechatUserInfoUpdateDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", wechatUser.getNickName());
            ext.put("wxid", wechatUser.getBizUserId());
            ext.put("userid", wechatUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员敏感信息报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }

        //修改ES缓存
        try{

            //修改营销策略数据
            if(flag_parent || flag_agent || flag_partner){
                marketingRewardsService.updateMarketingRewards(wechatUser);
            }

            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.DT_PC_WECHAT.getKey() + "_" + wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
            //查询会员基本信息
            Map<String,Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id, null);
            if(dataMp_ext != null){
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(wechatUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, wechatUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        }catch (Exception e){
            logger.error("修改会员营销策略信息出现异常:{}"+ e.getMessage());
        }

        //订阅信息。调用服务修改
    }

    /**
     * 用户发送消息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserSendMsgDto
     * @return null
     */
    @Transactional
    public void  sendMessageToOneUser(WechatUserSendMsgDto wechatUserSendMsgDto){

        if(wechatUserSendMsgDto.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        WechatUser wechatUser  = wechatUserMapper.selectById(wechatUserSendMsgDto.getId(), wechatUserSendMsgDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if(StringUtils.isBlank(wechatUserSendMsgDto.getMessage())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空 ");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(wechatUser.getDeviceUniqueId(), wechatUser.getDeviceType(), wechatUserSendMsgDto.getMerId());
        if(device == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        //调用API服务发送消息
        // TODO: 2021/9/4  发送消息
        //发送MQ消息
        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
        NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
        msgDto.setContent(noticeMsgDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(device.getRecvmsgType());
        msgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
        msgDto.setMerId(wechatUser.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
        noticeMsgDto.setContent(wechatUserSendMsgDto.getMessage());
        noticeMsgDto.setBizUserId(wechatUser.getBizUserId());
        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
        noticeMsgDto.setGroupId(null);
        noticeMsgDto.setNickName(wechatUser.getNickName());
        noticeMsgDto.setMsgSource(1);
        noticeMsgDto.setDelay(0);
        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
        noticeMsgPushProducerService.sendMessage(msgDto);

    }

    /**
     * 单个用户修改信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserUpdateDt
     * @return null
     */
    @Transactional
    public void updateToOneUser(WechatUserUpdateDto wechatUserUpdateDt){

        //修改时间
        int nowTime = DateUtil.getNowTime();

        if(wechatUserUpdateDt.getId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID不存在");
        }

        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserUpdateDt.getId(), wechatUserUpdateDt.getMerId());
        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        //修改用户类型
        //查询新的用户类型
        if(wechatUserUpdateDt.getUserType() != null){
            UserType userType_new = userTypeMapper.selectById(wechatUserUpdateDt.getUserType(), wechatUserUpdateDt.getMerId());
            //新会员类型不为空
            if(userType_new != null){
                if(userType_new.getId().longValue() != wechatUser.getUserType().longValue()){//修改了会员类型（修改了身份）
                    //需判断新会员类型是否跟旧会员类型在同一个组内，不同组内不能修改。否则会造成用户的会员类型组和绑定机器人配置方案里的会员类型组不一样
                    UserType userType_old = userTypeMapper.selectById(wechatUser.getUserType(), wechatUser.getMerId());
                    if(userType_old != null ){
                        if(userType_old.getGroupId().longValue() == userType_new.getGroupId().longValue()){ //如果不相等，表示不在同一个组内，则不让修改会员类型
                            UpdateIdentityDto updateIdentityDto = new UpdateIdentityDto();
                            updateIdentityDto.setMerId(wechatUserUpdateDt.getMerId());
                            updateIdentityDto.setId(wechatUser.getId());
                            updateIdentityDto.setUserTypeNew(wechatUserUpdateDt.getUserType());
                            updateIdentityDto.setIdentityNew(userType_new.getIdentity());
                            wechatUserTreeInfoService.updateIdentity(updateIdentityDto);
                        }
                    }
                }
            }
        }

        //修改定向规则
        //获取用户本身旧的定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRulesMap_old = JSONObject.parseObject(wechatUser.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>(){});
        if(priRewardRulesMap_old == null){
            priRewardRulesMap_old = new HashMap<>();
        }

        //获取页面设置的新的定向规则JSON对象
        Map<String, PriRewardRulesDto> priRewardRulesMap_new = JSONObject.parseObject(wechatUserUpdateDt.getPriRewardRules(), new TypeReference<Map<String, PriRewardRulesDto>>(){});
        if(priRewardRulesMap_new != null && priRewardRulesMap_new.size() > 0){
            for(String key : priRewardRulesMap_new.keySet()){
                //新定向规则
                PriRewardRulesDto priRewardRulesDto_new = priRewardRulesMap_new.get(key);
                //旧定向规则
                PriRewardRulesDto priRewardRulesDto_old = priRewardRulesMap_old.get(key);
                if(priRewardRulesDto_old == null){
                    priRewardRulesDto_old = new PriRewardRulesDto();
                }
                //判断新的定向规则值
                if(priRewardRulesDto_new != null){
                    //判断定向规则
                    if(priRewardRulesDto_new.getPriRuleId() != null){ //表示修改
                        if(priRewardRulesDto_new.getPriRuleId().longValue() < 0){ //表示清空
                            priRewardRulesDto_old.setPriRuleId(null);
                        }else{//表示修改
                            priRewardRulesDto_old.setPriRuleId(priRewardRulesDto_new.getPriRuleId());
                        }
                    }
                    //判断阶梯规则
                    if(priRewardRulesDto_new.getLadderId() != null){ //表示修改
                        if(priRewardRulesDto_new.getLadderId().longValue() < 0){ //表示清空
                            priRewardRulesDto_old.setLadderId(null);
                        }else{//表示修改
                            priRewardRulesDto_old.setLadderId(priRewardRulesDto_new.getLadderId());
                        }
                    }
                }
                //更新旧的定向规则
                priRewardRulesMap_old.put(key, priRewardRulesDto_old);
            }
        }
        //修改定向规则
        wechatUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRulesMap_old)));
        wechatUserMapper.updatePriRewardRules(wechatUser);

        //是否增加新标签列表
        List<String> userLabList = wechatUserUpdateDt.getUserLabList();
        //是否清空所有标签
        Integer cleanLab = wechatUserUpdateDt.getCleanLab();
        //清空指定标签列表
        List<String> cleanUserLabList = wechatUserUpdateDt.getCleanUserLabList();

        //开启清空所有标签
        if(cleanLab != null && cleanLab.intValue() == 1){
            //添加新标签
            if(userLabList != null && userLabList.size() > 0){
                wechatUser.setTags(JSONObject.toJSONString(userLabList));
            }else{
                wechatUser.setTags("");
            }
        }else{ //未开启清空标签
            //旧标签
            String tags_old = wechatUser.getTags();
            List<String> tagsOldList = JSONObject.parseArray(tags_old, String.class);
            if(tagsOldList == null){
                tagsOldList = new ArrayList<>();
            }

            //清空指定标签列表
            if(cleanUserLabList != null && cleanUserLabList.size() > 0){
                tagsOldList.removeAll(cleanUserLabList);
            }

            //添加新标签
            if(userLabList != null && userLabList.size() > 0){
                tagsOldList.addAll(userLabList);
            }

            //去重复
            tagsOldList = tagsOldList.stream().distinct().collect(Collectors.toList());
            wechatUser.setTags(JSONObject.toJSONString(tagsOldList));
        }

        //是否增加新会员标签列表
        List<SysTagVo> sysTagsList = wechatUserUpdateDt.getSysTagsList();
        //是否清空所有会员标签
        Integer cleanSysTags = wechatUserUpdateDt.getCleanSysTags();
        //清空指定会员标签列表
        List<SysTagVo> cleanSysTagsList = wechatUserUpdateDt.getCleanSysTagsList();

        //开启清空所有会员标签
        if(cleanSysTags != null && cleanSysTags.intValue() == 1){
            //添加新会员标签
            if(sysTagsList != null && sysTagsList.size() > 0){
                wechatUser.setSysTags(JSONObject.toJSONString(sysTagsList));
            }else{
                wechatUser.setSysTags("");
            }
        }else{//未开启清空会员标签
            //旧会员标签
            String sysTags_old = wechatUser.getSysTags();
            List<SysTagVo> sysTagsOldList = JSONObject.parseArray(sysTags_old, SysTagVo.class);
            if(sysTagsOldList == null){
                sysTagsOldList = new ArrayList<>();
            }

            //清空指定会员标签列表
            if(cleanSysTagsList != null && cleanSysTagsList.size() > 0){
                sysTagsOldList.removeAll(cleanSysTagsList);
            }

            //添加新会员标签
            if(sysTagsList != null && sysTagsList.size() > 0){
                if(sysTagsOldList.size() == 0){
                    sysTagsOldList.addAll(sysTagsList);
                }else{
                    //循环遍历，一个个增加,如果类型存在，则删除
                    for (SysTagVo sysTagVo : sysTagsList) {
                        for (int i = sysTagsOldList.size()-1; i>=0 ; i--) {
                            //如果标签类型相等，则删除旧标签
                            if(sysTagsOldList.get(i).getType().intValue() == sysTagVo.getType().intValue()){
                                sysTagsOldList.remove(i);
                            }else{
                                if(sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE){
                                    if(sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE){
                                        sysTagsOldList.remove(i);
                                    }
                                }else if(sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE){
                                    if(sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE){
                                        sysTagsOldList.remove(i);
                                    }
                                }
                            }
                        }
                    }
                    sysTagsOldList.addAll(sysTagsList);
                }
            }

            //去重复
            sysTagsOldList = sysTagsOldList.stream().distinct().collect(Collectors.toList());
            wechatUser.setSysTags(JSONObject.toJSONString(sysTagsOldList));
        }


        //是否修改备注
        Boolean setRemarkFlag = false;
        String userRemark = wechatUserUpdateDt.getUserRemark();
        if(StringUtils.isNotBlank(userRemark)){
            //替换变量
            userRemark = userRemark.replaceFirst("\\[昵称\\]", wechatUser.getNickName());
            wechatUser.setRemark(Tools.getStr(userRemark));
            setRemarkFlag = true;
        }

        wechatUserMapper.updateRemarkAndTags(wechatUser);

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if(setRemarkFlag){
            //查询机器人
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), wechatUser.getMerId());
            if(deviceWechatInfo != null){
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setMerId(wechatUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(wechatUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(wechatUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }

        //计算用户余额并修改
        //变更余额
        Double balance = wechatUserUpdateDt.getBalance();
        //变更积分
        Integer integral = wechatUserUpdateDt.getIntegral();
        //积分和余额只要有一个不等于null。表示有变更，则修改
        if(balance != null || integral != null){
            //发送修改会员数据提醒通知
            StringBuffer content = new StringBuffer("正在修改会员余额和积分;");
            wechatUser.setUpdateTime(nowTime);
            Double changeBalance = 0.0D;
            //表示修改余额
            if(balance != null){
                //修改类型类型
                Integer balanceType = wechatUserUpdateDt.getBalanceType();
                //旧余额
                Double oldBalance = Tools.getDouble(wechatUser.getBalance());
                //新余额
                Double newBalance = 0.00D;
                if(balanceType.intValue() == -1){ //减量
                    //减少
                    newBalance = Math.sub(oldBalance, balance);
                    changeBalance = Math.sub(0, balance);
                }else if(balanceType.intValue() == 1){ //增量
                    //增加
                    newBalance = Math.add(oldBalance, balance);
                    changeBalance = balance;
                }else{//修改成指定值
                    newBalance = balance;
                    changeBalance = Math.sub(newBalance, oldBalance);
                }
                wechatUser.setBalance(newBalance);
                content.append("变动余额:" + changeBalance).append(";");
            }

            //变更积分
            Integer changeIntegral = 0;
            if(integral != null) {
                //修改积分类型
                Integer integralType = wechatUserUpdateDt.getIntegralType();
                //旧积分
                Integer oldIntegral = Tools.getInteger(wechatUser.getIntegral());
                //新积分
                Integer newIntegral = 0;

                if(integralType.intValue() == -1){ //减量
                    //减少
                    newIntegral = oldIntegral - integral;
                    changeIntegral = 0 - integral;
                }else if(integralType.intValue() == 1){ //增量
                    //增加
                    newIntegral = oldIntegral + integral;
                    changeIntegral = integral;
                }else{//修改成指定值
                    newIntegral = integral;
                    changeIntegral = newIntegral - oldIntegral;
                }
                wechatUser.setIntegral(newIntegral);
                content.append("变动积分:" + changeIntegral).append(";");
            }

            int j = wechatUserMapper.updateBalance(wechatUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
            //增加账号入账明细
            UserAccDetail wechatUserAccDetail = new UserAccDetail();
            wechatUserAccDetail.setId(IdWorker.getId());
            wechatUserAccDetail.setMerId(wechatUser.getMerId());
            wechatUserAccDetail.setUserId(wechatUser.getId());
            wechatUserAccDetail.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
            wechatUserAccDetail.setDeviceType(wechatUser.getDeviceType());
            wechatUserAccDetail.setChangeInte(changeIntegral);
            wechatUserAccDetail.setChangeBal(changeBalance);
            wechatUserAccDetail.setNewBal(wechatUser.getBalance());
            wechatUserAccDetail.setNewInte(wechatUser.getIntegral());
            wechatUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
            wechatUserAccDetail.setRemark("运营商人为操作批量修改");
            wechatUserAccDetail.setCreateTime(nowTime);
            wechatUserAccDetail.setUpdateTime(nowTime);
            //插入用户账户明细记录
            int insert = userAccDetailMapper.insert(wechatUserAccDetail);
            if(insert!=1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
            }

            //发送异常报警通知-修改会员敏感信息
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(wechatUser.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, wechatUserUpdateDt.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            if(loginVo == null){
                loginVo = new LoginVo();
            }
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", wechatUser.getNickName());
            ext.put("wxid", wechatUser.getBizUserId());
            ext.put("userid", wechatUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
        }

        //是否加入黑名单
        if(wechatUserUpdateDt.getUserBlackType() != null){
            //查询是否已经在黑名单当中
            //id为merId_wxid
            String id = wechatUser.getMerId() + "_" + wechatUser.getBizUserId();
            Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
            WechatBlacklistPrv wechatBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
            //不存在，则表示还未加入黑名单，则加入
            if(wechatBlacklistPrv == null){
                wechatBlacklistPrv = new WechatBlacklistPrv();
                wechatBlacklistPrv.setId(id);
                wechatBlacklistPrv.setMerId(wechatUser.getMerId());
                wechatBlacklistPrv.setDeviceUniqueId(wechatUser.getDeviceUniqueId());
                wechatBlacklistPrv.setDeviceType(wechatUser.getDeviceType());
                wechatBlacklistPrv.setWxid(wechatUser.getBizUserId());
                wechatBlacklistPrv.setNickName(wechatUser.getNickName());
                wechatBlacklistPrv.setHeadImg(wechatUser.getHeadImg());
                wechatBlacklistPrv.setType(wechatUserUpdateDt.getUserBlackType());
                wechatBlacklistPrv.setRemark(wechatUserUpdateDt.getUserBlackRemark());
                wechatBlacklistPrv.setCreateTime(nowTime);
                wechatBlacklistPrv.setUpdateTime(nowTime);
                elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);
            }

            //添加到全网黑名单
            if(wechatUserUpdateDt.getAllBackFlag() != null && wechatUserUpdateDt.getAllBackFlag().intValue() == 1){
                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if(wechatBlacklistPub == null){
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(wechatUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(nowTime);
                    wechatBlacklistPub.setUpdateTime(nowTime);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, wechatUser.getBizUserId());
                }
            }

        }

        //是否加入提现黑名单
        if(Tools.getInteger(wechatUserUpdateDt.getTakeBalBlackFlag()).intValue() == 1){//开启加入提现黑名单

            //判断会员id是否已经在黑名单当中
            TakeBalBlacklist takeBalBlacklist_old = takeBalBlacklistMapper.selectByUserId(wechatUserUpdateDt.getId(), wechatUserUpdateDt.getMerId());
            //不存在，则加入黑名单当中
            if(takeBalBlacklist_old == null){
                TakeBalBlacklist takeBalBlacklist = new TakeBalBlacklist();
                takeBalBlacklist.setUserId(wechatUserUpdateDt.getId());
                takeBalBlacklist.setMerId(wechatUserUpdateDt.getMerId());
                takeBalBlacklist.setNickName(wechatUser.getNickName());
                takeBalBlacklist.setDeviceType(wechatUser.getDeviceType());
                takeBalBlacklist.setRemark(wechatUserUpdateDt.getTakeBalBlackRemark());
                takeBalBlacklist.setAlipayAccount(wechatUser.getAlipayAccount());
                takeBalBlacklist.setId(IdWorker.getId());
                takeBalBlacklist.setCreateTime(nowTime);
                takeBalBlacklist.setUpdateTime(nowTime);
                //保存加入提现黑名单
                takeBalBlacklistMapper.insert(takeBalBlacklist);
            }
        }

        // 添加营销黑名单
        try {
            marketingRewardsBlackListService.addOrRemoveByFlag(wechatUser.getMerId(), String.valueOf(wechatUser.getId()), wechatUserUpdateDt.getMarketingRewardsBlackListRemark(), wechatUserUpdateDt.getMarketingRewardsBlackListFlag(),
                    wechatUserUpdateDt.getSubNotPassFriend());
        }catch (Exception e){

        }

    }

    /**
     * 单个用户定投筛选
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserOptCpcDto
     * @return null
     */
    @Transactional
    public void optCpcToOneUser(WechatUserOptCpcDto wechatUserOptCpcDto){

        if(wechatUserOptCpcDto.getId() == null ){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户id不存在");
        }

        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserOptCpcDto.getId(), wechatUserOptCpcDto.getMerId());

        if(wechatUser == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if(wechatUserOptCpcDto.getCpaId() == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
        }

        //操作定投筛选功能
        // TODO: 2022/2/24

    }

    /**
     * 更新微信信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param wechatUserIdDto
     * @return null
     */
    public WechatUserInfoVo updateUserInfoFromWechat(WechatUserIdDto wechatUserIdDto){

        //返回页面对象
        WechatUserInfoVo wechatUserInfoVo = new WechatUserInfoVo();

        if(wechatUserIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        WechatUser wechatUser = wechatUserMapper.selectById(wechatUserIdDto.getId(), wechatUserIdDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        if(wechatUser.getDeviceUniqueId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员未绑定机器人信息");
        }

        //从ES中获取个人微信信息
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(wechatUser.getDeviceUniqueId(), wechatUserIdDto.getMerId());

        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员绑定的机器人不存在或者已经删除");
        }

        if(StringUtils.isNotBlank(deviceWechatInfo.getDeviceId())){
            String esId = wechatUser.getMerId() + "_" + deviceWechatInfo.getDeviceId() + "_" + wechatUser.getBizUserId();
            try{
                //通过查询运营商其他索引分片获取分片索引
                String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
                uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wechatUserIdDto.getMerId());
                Map<String,Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, esId, null);
                WxContactsInfoVo wxContactsInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxContactsInfoVo.class);
                if(wxContactsInfoVo != null){
                    //更新微信信息
                    wechatUser.setNickName(wxContactsInfoVo.getNick());
                    wechatUser.setHeadImg(wxContactsInfoVo.getHimg());
                    wechatUser.setRemark(wxContactsInfoVo.getRemark());
                    wechatUserMapper.updateById(wechatUser);
                }
            } catch (Exception e){
                logger.error("从ES中查询通讯录:error:"+e.getMessage());
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新微信信息失败");
            }
        }

        BeanUtils.copyProperties(wechatUser, wechatUserInfoVo);
        return wechatUserInfoVo;
    }

    /**
     * 修改互通的公众号会员的公众号
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateWxpubUserDto
     * @return null
     */
    public void updateInterflowWxpubUser(UpdateWxpubUserDto updateWxpubUserDto){
        //个人微信用户id
        Long id = updateWxpubUserDto.getId();
        //对应新的公众号id
        Long wxpubDeviceUniqueId = updateWxpubUserDto.getWxpubDeviceUniqueId();


        if(id == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人微信id不能为空");
        }

        if(wxpubDeviceUniqueId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新公众号id不能为空");
        }

        WechatUser wechatUser = wechatUserMapper.selectById(id, updateWxpubUserDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        String uzaiUnionId = wechatUser.getUzaiUnionId();

        if(StringUtils.isBlank(uzaiUnionId)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通公众号");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(uzaiUnionId, wechatUser.getMerId());
        if(wxpubUser == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通公众号");
        }

        WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubDeviceUniqueId);
        if(wxpubInfoEntity == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该公众号不存在或已删除");
        }

        wxpubUser.setDeviceUniqueId(wxpubDeviceUniqueId);
        wxpubUserMapper.updateDevice(wxpubUser);

    }


    /**
     * 清除会员的互通信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param cleanUserUnionIdDto
     * @return null
     */
    public void cleanUserUnionId(CleanUserUnionIdDto cleanUserUnionIdDto){
        Long merId = cleanUserUnionIdDto.getMerId();
        //来源会员id
        Long sourceUserId = cleanUserUnionIdDto.getSourceUserId();
        //来源设备类型（private_wechat：个人微信； work_wechat：企业微信；  wx_pub：公众号）
        String sourceDeviceType = cleanUserUnionIdDto.getSourceDeviceType();
        //需要解除会员id
        Long cleanUserId = cleanUserUnionIdDto.getCleanUserId();
        //需要解除的设备类型（private_wechat：个人微信； work_wechat：企业微信；  wx_pub：公众号）
        String cleanDeviceType = cleanUserUnionIdDto.getCleanDeviceType();

        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统参数错误");
        }

        if(sourceUserId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入来源会员id");
        }
        if(StringUtils.isBlank(sourceDeviceType)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入来源设备类型");
        }
        if(cleanUserId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入需要解除的会员id");
        }
        if(StringUtils.isBlank(cleanDeviceType)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入需要解除的设备类型");
        }

        //判断需要清除的设备类型为公众号，则需要清理来源会员的unionId
        if(DeviceTypeEnum.WX_PUB.getKey().equals(cleanDeviceType)){
            if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(sourceDeviceType)){ //来源是个人微信
                WechatUser wechatUser = wechatUserMapper.selectById(sourceUserId, merId);
                if(wechatUser != null){
                    wechatUser.setUzaiUnionId(String.valueOf(wechatUser.getId()));
                    wechatUserMapper.updateUzaiUnionId(wechatUser);
                }
            }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(sourceDeviceType)){ //来源是企业微信
                WxworkUser wxworkUser = wxworkUserMapper.selectById(sourceUserId, merId);
                if(wxworkUser != null){
                    wxworkUser.setUzaiUnionId(String.valueOf(wxworkUser.getId()));
                    wxworkUserMapper.updateUzaiUnionId(wxworkUser);
                }
            }
        }else{//不是清空公众号互通信息，则直接清除该会员的互通信息
            if(DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(cleanDeviceType)){ //清除个人微信
                WechatUser wechatUser = wechatUserMapper.selectById(cleanUserId, merId);
                if(wechatUser != null){
                    wechatUser.setUzaiUnionId(String.valueOf(wechatUser.getId()));
                    wechatUserMapper.updateUzaiUnionId(wechatUser);
                }
            }else if(DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(cleanDeviceType)){ //清除企业微信
                WxworkUser wxworkUser = wxworkUserMapper.selectById(cleanUserId, merId);
                if(wxworkUser != null){
                    wxworkUser.setUzaiUnionId(String.valueOf(wxworkUser.getId()));
                    wxworkUserMapper.updateUzaiUnionId(wxworkUser);
                }
            }
        }
    }

    /**
     * 修改会员订阅信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateSubscribeInfoDto
     * @return null
     */
    @Transactional
    public void updateSubscribeInfo(UpdateSubscribeInfoDto updateSubscribeInfoDto){
        //个人微信用户id
        Long id = updateSubscribeInfoDto.getId();

        WechatUser wechatUser = wechatUserMapper.selectById(id, updateSubscribeInfoDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        wechatUser.setSubscribeInfo(updateSubscribeInfoDto.getSubscribeInfo());

        //修改会员订阅信息
        wechatUserMapper.updateSubscribeInfo(wechatUser);

    }

    /**
     * 修改会员营销奖励信息
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param updateMarketingRewardDto
     * @return null
     */
    @Transactional
    public void updateMarketingReward(UpdateMarketingRewardDto updateMarketingRewardDto){
        //个人微信用户id
        Long userId = updateMarketingRewardDto.getId();

        WechatUser wechatUser = wechatUserMapper.selectById(userId, updateMarketingRewardDto.getMerId());

        if(wechatUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //页面修改的营销策略
        MarketingRewardVo marketingReward = updateMarketingRewardDto.getMarketingReward();
        if(marketingReward == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入营销奖励信息");
        }

        //获取该会员的营销策略数据
        String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
        String marketingRewardId = StringUtils.join(wechatUser.getId(), wechatUser.getRegSource());
        Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
        MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
        if(marketingRewardVo == null){
            marketingRewardVo = new MarketingRewardVo(true);
        }
        marketingRewardVo.setId(marketingRewardId);

        String tradeno_old = StringUtils.join(userId, wechatUser.getRegSource());
        int now = DateUtil.getNowTime();

        //添加好友奖励
        if(marketingReward.getAddRe() != null){
            //页面传递对象
            MarketingRewardVo.ReDetail addRe =  marketingReward.getAddRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail addReVo =  marketingRewardVo.getAddRe();
            if(addReVo == null){
                addReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(addRe, addReVo, CopyOptions.create().ignoreNullValue());
            addReVo.setUserId(wechatUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setAddRe(addReVo);

            //奖励状态 0未奖励，1已奖励,
            if(addRe.getStatus() != null && addRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(addRe.getReBal()) > 0 || Tools.getInteger(addRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_REGIST.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REGISTER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励下级
        if(marketingReward.getBindRe() != null){
            MarketingRewardVo.ReDetail bindRe =  marketingReward.getBindRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReVo =  marketingRewardVo.getBindRe();
            if(bindReVo == null){
                bindReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindRe, bindReVo, CopyOptions.create().ignoreNullValue());
            //设置会员id
            bindReVo.setUserId(wechatUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindRe(bindReVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindRe.getStatus() != null && bindRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindRe.getReBal()) > 0 || Tools.getInteger(bindRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_INVITE.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励上级
        if(marketingReward.getBindReParent() != null){
            MarketingRewardVo.ReDetail bindReParent =  marketingReward.getBindReParent();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReParentVo =  marketingRewardVo.getBindReParent();
            if(bindReParentVo == null){
                bindReParentVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindReParent, bindReParentVo, CopyOptions.create().ignoreNullValue());
            bindReParentVo.setUserId(wechatUser.getParentId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindReParent(bindReParentVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindReParent.getStatus() != null && bindReParent.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindReParent.getReBal()) > 0 || Tools.getInteger(bindReParent.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //查询上级会员id
                    Long parentUserId = wechatUser.getParentId();

                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(parentUserId, AccDetailTypeEnum.REWARD_INVITE_PARENT.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(parentUserId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定代理，奖励代理
        if(marketingReward.getBindReAgent() != null){
            MarketingRewardVo.ReDetail bindReAgent =  marketingReward.getBindReAgent();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindReAgentVo =  marketingRewardVo.getBindReAgent();
            if(bindReAgentVo == null){
                bindReAgentVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindReAgent, bindReAgentVo, CopyOptions.create().ignoreNullValue());
            //更新会员id
            bindReAgentVo.setUserId(wechatUser.getAgentId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindReAgent(bindReAgentVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindReAgent.getStatus() != null && bindReAgent.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindReAgent.getReBal()) > 0 || Tools.getInteger(bindReAgent.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引

                    //查询代理人id
                    Long agentUserId = wechatUser.getAgentId();

                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(agentUserId, AccDetailTypeEnum.REWARD_ORDER_AGENT.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_AGENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(agentUserId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定合伙人，奖励合伙人
        if(marketingReward.getBindRePartner() != null){
            MarketingRewardVo.ReDetail bindRePartner =  marketingReward.getBindRePartner();
            //ES缓存对象
            MarketingRewardVo.ReDetail bindRePartnerVo =  marketingRewardVo.getBindRePartner();
            if(bindRePartnerVo == null){
                bindRePartnerVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(bindRePartner, bindRePartnerVo, CopyOptions.create().ignoreNullValue());
            //更新会员id
            bindRePartnerVo.setUserId(wechatUser.getPartnerId());
            //更新会员的营销奖励数据
            marketingRewardVo.setBindRePartner(bindRePartnerVo);

            //奖励状态 0未奖励，1已奖励,
            if(bindRePartner.getStatus() != null && bindRePartner.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(bindRePartner.getReBal()) > 0 || Tools.getInteger(bindRePartner.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引

                    //查询代理人id
                    Long partnerId = wechatUser.getPartnerId();

                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(partnerId, AccDetailTypeEnum.REWARD_ORDER_PARTNER.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARTNER.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(partnerId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首查奖励
        if(marketingReward.getFirstQueryRe() != null){
            MarketingRewardVo.ReDetail firstQueryRe =  marketingReward.getFirstQueryRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstQueryReVo =  marketingRewardVo.getFirstQueryRe();
            if(firstQueryReVo == null){
                firstQueryReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstQueryRe, firstQueryReVo, CopyOptions.create().ignoreNullValue());
            //更新会员id
            firstQueryReVo.setUserId(wechatUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstQueryRe(firstQueryReVo);

            //奖励状态 0未奖励，1已奖励,
            if(firstQueryRe.getStatus() != null && firstQueryRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(firstQueryRe.getReBal()) > 0 || Tools.getInteger(firstQueryRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_QUERY.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_QUERY_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首单奖励
        if(marketingReward.getFirstOrderRe() != null){
            MarketingRewardVo.ReDetail firstOrderRe =  marketingReward.getFirstOrderRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstOrderReVo =  marketingRewardVo.getFirstOrderRe();
            if(firstOrderReVo == null){
                firstOrderReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstOrderRe, firstOrderReVo, CopyOptions.create().ignoreNullValue());
            //更新会员id
            firstOrderReVo.setUserId(wechatUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstOrderRe(firstOrderReVo);

            //奖励状态 0未奖励，1已奖励,
            if(firstOrderRe.getStatus() != null &&firstOrderRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(firstOrderRe.getReBal()) > 0 || Tools.getInteger(firstOrderRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_ORDER.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_ORDER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首次收货奖励
        if(marketingReward.getFirstSettledRe() != null){
            MarketingRewardVo.ReDetail firstSettledRe =  marketingReward.getFirstSettledRe();
            //ES缓存对象
            MarketingRewardVo.ReDetail firstSettledReVo =  marketingRewardVo.getFirstSettledRe();
            if(firstSettledReVo == null){
                firstSettledReVo = new MarketingRewardVo.ReDetail();
            }
            //复制对象值忽略null值
            BeanUtil.copyProperties(firstSettledRe, firstSettledReVo, CopyOptions.create().ignoreNullValue());
            //更新会员id
            firstSettledReVo.setUserId(wechatUser.getId());
            //更新会员的营销奖励数据
            marketingRewardVo.setFirstSettledRe(firstSettledReVo);

            //奖励状态 0未奖励，1已奖励,
            if(firstSettledRe.getStatus() != null && firstSettledRe.getStatus() == 0){ //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if(Tools.getDouble(firstSettledRe.getReBal()) > 0 || Tools.getInteger(firstSettledRe.getReInte()) > 0){//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_SETTLE.getValue(), tradeno_old);
                    if(userAccDetail != null){ //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_SETTLED_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, wechatUser.getMerId());
                    if(redPacket != null){ //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHH");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if(i != 1){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //修改营销数据ES
        elasticsearchUtil.addDataForObjectSerializer(marketingRewardVo, uzai_marketing_reward_info, tradeno_old);

    }

}
